Use MONTH() and YEAR() for this. Let us first create a table −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, ShippingDate datetime ); Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(ShippingDate) values('2019-01-21 10:40:21'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(ShippingDate) values('2015-07-01 11:15:30'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(ShippingDate) values('2012-12-31 10:45:56'); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+---------------------+ | Id | ShippingDate | +----+---------------------+ | 1 | 2019-01-21 10:40:21 | | 2 | 2015-07-01 10:40:20 | | 3 | 2012-12-31 10:45:56 | +----+---------------------+ 3 rows in set (0.00 sec)
Following is the query to search results by MONTH and YEAR −
mysql> select *from DemoTable where MONTH(ShippingDate)=7 and YEAR(ShippingDate)=2015;
This will produce the following output −
+----+---------------------+ | Id | ShippingDate | +----+---------------------+ | 2 | 2015-07-01 11:15:30 | +----+---------------------+ 1 row in set (0.03 sec)