How to Use the YEAR() Function in MySQL

Contents
In this article, you will learn how to use the YEAR() function in MySQL.
Using the YEAR() function in MySQL
In MySQL, the YEAR() function is used to extract the year from a date. The function returns the year as an integer value.
Syntax
YEAR(date);
where date is the input date in any valid date format.
Examples
Here are some examples of using the YEAR() function in MySQL:
Extracting the year from a date string
To extract the year from a date string, you can pass the string as an argument to the YEAR() function.
Syntax
SELECT YEAR('2022-05-15');
Example
SELECT YEAR('2022-05-15');
Output:
+------------------+
| YEAR('2022-05-15') |
+------------------+
| 2022 |
+------------------+
Extracting the year from a date column in a table
To extract the year from a date column in a table, you can use the YEAR() function in the SELECT statement.
Syntax
SELECT YEAR(date_column) FROM table_name;
Example
Consider a table orders with columns order_id, order_date, and order_total. To extract the year from the order_date column, you can use the following query:
SELECT YEAR(order_date) FROM orders;
Output:
+---------------+
| YEAR(order_date) |
+---------------+
| 2022 |
| 2021 |
| 2021 |
| 2022 |
+---------------+
Using YEAR() function with WHERE clause
You can also use the YEAR() function in a WHERE clause to filter records based on the year.
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE YEAR(date_column) = year_value;
Example
To select orders placed in the year 2022, you can use the following query:
SELECT order_id, order_total
FROM orders
WHERE YEAR(order_date) = 2022;
Output:
+----------+-------------+
| order_id | order_total |
+----------+-------------+
| 1001 | 250.00 |
| 1004 | 125.00 |
+----------+-------------+