MySQL YEAR() function; Through this tutorial, we will learn how to use MySQL YEAR() function with the help of examples.
When we want to filter data year wise from MySQL queries that time we could use MySQL year() function.
For example, if you want to fetch current year data from a mysql database or you want to fetch last year’s data from MySQL database, in that case, you can use MySQL year() function. Here we will also take an example of how to get current year data and year wise data from MySQL database.
MySQL YEAR() Function
In MySQL, the YEAR() is used to return the “year” part of the given date. It will return value year like 2018,2019 etc.
Syntax
The YEAR() function syntax is:
YEAR(argument)
Here :
- The argument is the date you want the YEAR to return.
Example-1
Now we take an example to demonstrate.
SELECT YEAR('2020-06-18') AS 'Result';
Output-1
+--------+ | Result | +--------+ | 2020 | +--------+
Example-2
SELECT YEAR('2022-10-18') AS 'Result';
Output-2
+--------+ | Result | +--------+ | 2022 | +--------+
Example-3 | Current Year Record
Next database example, we take an example of getting the current year data from the MySQL database.
SELECT name, YEAR(CURDATE())
FROM employees
WHERE YEAR(created_at) = YEAR(NOW()) ORDER BY id
DESC
Output-3
Example-4 | Current Date/Time
Let’s take another example, extracting part of the YEAR part from the current date and time (which is now returned using the () function).
SELECT NOW(), YEAR(NOW());
Output-4
+---------------------+--------------------+ | NOW() | YEAR(NOW()) | +---------------------+--------------------+ | 2019-07-10 18:30:44 | 2019 | +---------------------+--------------------+
Example-6 | CURDATE() Function
Let’s take another example of using CURDATE() function. Basically CURDATE() function returns only the date without time.
SELECT CURDATE(), YEAR(CURDATE());
Output-6
+------------+-----------------------+ | CURDATE() | YEAR(CURDATE()) | +------------+-----------------------+ | 2019-05-15 | 2019 | +------------+-----------------------+
Example-7 | Year Wise Data
You want to fetch year-wise data. Use the below query for getting year-wise data from the mysql database table.
SELECT COUNT(id) as Count,YEAR(created_at) as Year FROM employees GROUP BY YEAR(created_at)
Conclusion
Here, you have learned how to use MySQL YEAR() function with various examples.
Recommended MySQL Tutorials
If you have any questions or thoughts to share, use the comment form below to reach us.