MySQL query to fetch record by year


To fetch record by year, use the YEAR() method in MySQL −

select *from yourTableName
where year(yourColumnName)=yourYearValue;

Let us first create a table −

mysql> create table DemoTable
-> (
-> CustomerName varchar(100),
-> ShippingDate datetime
-> );
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris','2019-01-21');
Query OK, 1 row affected (0.28 sec)

mysql> insert into DemoTable values('Robert','2018-02-21');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values('David','2016-04-01');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+--------------+---------------------+
| CustomerName | ShippingDate        |
+--------------+---------------------+
| Chris        | 2019-01-21 00:00:00 |
| Robert       | 2018-02-21 00:00:00 |
| David        | 2016-04-01 00:00:00 |
+--------------+---------------------+
3 rows in set (0.00 sec)

Following is the query to fetch record by year −

mysql> select *from DemoTable
-> where year(ShippingDate)=2016;

Output

This will produce the following output −

+--------------+---------------------+
| CustomerName | ShippingDate        |
+--------------+---------------------+
| David        | 2016-04-01 00:00:00 |
+--------------+---------------------+
1 row in set (0.04 sec)

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 30-Jun-2020

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements