Tuesday, December 24, 2024

MySQL YEAR() Function

 The YEAR() function in MySQL is used to extract the year from a given date or datetime value. It returns the year as a four-digit number (e.g., 2024 for the year 2024). This function is particularly useful when you want to retrieve or filter records based on the year.

Syntax

YEAR(date)
  • date: The date or datetime value from which the year will be extracted.

Example Queries

1. Extract the year from a date

SELECT YEAR('2024-12-24') AS extracted_year;

Output:

+----------------+
| extracted_year |
+----------------+
|           2024 |
+----------------+

2. Use with a datetime value

SELECT YEAR('2024-12-24 15:30:45') AS extracted_year;

Output:

+----------------+
| extracted_year |
+----------------+
|           2024 |
+----------------+

3. Use in a WHERE clause

Suppose you have a table named orders with a column order_date. To find all orders from the year 2024:

SELECT * 
FROM orders
WHERE YEAR(order_date) = 2024;

4. Use with the current date

To extract the current year:

SELECT YEAR(CURDATE()) AS current_year;

Output:

+--------------+
| current_year |
+--------------+
|         2024 |
+--------------+

Notes

  • If the input to the YEAR() function is invalid or NULL, it returns NULL.
  • The function works on both DATE and DATETIME data types.

Let me know if you need more examples or further explanations!

No comments:

Post a Comment