The MySQL YEAR function is a date and time function used to extract the year from a given date. It is particularly useful when you want to retrieve only the year portion of a date value stored in a MySQL database.
Syntax
The syntax for the YEAR function is quite straightforward:
YEAR(date)
Here, the date parameter represents the date or datetime value from which you want to extract the year.
Example
Let’s look at a simple example:
SELECT YEAR('2022-01-01') AS extracted_year;
In this example, the YEAR function is applied to the date ‘2022-01-01’, and the result is a single-column result set with the alias extracted_year containing the value ‘2022’.
You can also use the YEAR function with columns from a table. Consider the following table named orders:
+---------+-------------+ | order_id | order_date | +---------+-------------+ | 1 | 2022-01-15 | | 2 | 2023-05-20 | | 3 | 2021-09-08 | +---------+-------------+
To retrieve the years from the order_date column, you can use the YEAR() function as follows:
SELECT order_id, YEAR(order_date) AS order_year FROM orders;
The result would be:
+---------+-------------+ | order_id | order_year | +---------+-------------+ | 1 | 2022 | | 2 | 2023 | | 3 | 2021 | +---------+-------------+
This example demonstrates how the YEAR function can be employed to extract the year component from a date or datetime column, facilitating the retrieval of specific information based on the temporal aspect of the data.
It’s important to note that the YEAR function only considers the year portion of the date and discards the month and day components. Additionally, it operates on the assumption that the provided input is a valid date or datetime format; otherwise, unexpected results may occur.