For year and month date fetching, you can use YEAR() and MONTH() function in MySQL. 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.48 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(ShippingDate) values('2019-01-31'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(ShippingDate) values('2018-12-01'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(ShippingDate) values('2019-06-02'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable(ShippingDate) values('2019-11-18'); Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
+----+-----------------------+ | Id | ShippingDate | +----+-----------------------+ | 1 | 2019-01-31 00 :00 :00 | | 2 | 2018-12-01 00 :00 :00 | | 3 | 2019-06-02 00 :00 :00 | | 4 | 2019-11-18 00 :00 :00 | +----+-----------------------+ 4 rows in set (0.00 sec)
Following is the query to fetch date on the basis of a specific year and month −
mysql> select *from DemoTable where ( year(ShippingDate)='2019') and (month(ShippingDate)='06');
Output
+----+-----------------------+ | Id | ShippingDate | +----+-----------------------+ | 3 | 2019-06-02 00 :00 :00 | +----+-----------------------+ 1 row in set (0.07 sec)