MySQL to fetch records based on a specific month and year?


For this, use MONTH() and YEAR(). Let us first create a table −

mysql> create table DemoTable1846
     (
     PurchaseDate date
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1846 values('2019-01-10');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1846 values('2019-12-24');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1846 values('2018-09-21');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1846 values('2017-10-26');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1846;

This will produce the following output −

+--------------+
| PurchaseDate |
+--------------+
| 2019-01-10   |
| 2019-12-24   |
| 2018-09-21   |
| 2017-10-26   |
+--------------+
4 rows in set (0.00 sec)

Here is the query to fetch records based on a specific month and year

mysql> select * from DemoTable1846
     where month(PurchaseDate)=12
     and year(PurchaseDate)=2019;

This will produce the following output −

+--------------+
| PurchaseDate |
+--------------+
| 2019-12-24   |
+--------------+
1 row in set (0.00 sec)

Updated on: 26-Dec-2019

602 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements