The YEAR() function in MySQL extracts the year part from a given date or datetime value. It returns the year as a four-digit number (ranging from 1000 to 9999).
Definition and Usage
- Purpose: The function returns the year part of a date or datetime value.
- Note: The result is a four-digit number representing the year.
Syntax
YEAR(date)
- Parameters:
- date: Required. The date or datetime value from which you want to extract the year.
Technical Details
- Works in: From MySQL 4.0 onwards.
- Return Type: Returns an integer (the year), which is a number from 1000 to 9999.
Examples
Example 1: Return the year part of a specific date
SELECT YEAR("2017-06-15");
Result:
2017
Explanation: The year of the date June 15, 2017, is 2017.
Example 2: Return the year part of a datetime value
SELECT YEAR("2017-06-15 09:34:21");
Result:
2017
Explanation: The year part of the datetime 2017-06-15 09:34:21 is 2017.
Example 3: Return the year part of the current system date
SELECT YEAR(CURDATE());
Result:
<current year>
Explanation: This will return the current year (based on the system's date).
Use Cases
- Date Analysis: Useful when you need to extract just the year from a date or datetime value.
- Filtering by Year: Can be used in SQL queries to filter data by year, for example, when generating yearly reports.
- Calculations Involving Years: You can use this function for calculations involving time intervals (e.g., the number of years between two dates).
Related Functions
MONTH(): Extracts the month part of a date or datetime.DAY(): Extracts the day part of a date or datetime.YEARWEEK(): Returns the year and week number for a date.