Tutorialspoint

1 Answer
Sharon Christine

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;

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;

This will produce the following output −

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.