MySQL SELECT query to return records with specific month and year

MySQLMySQLi Database

For specific month, use MONTH() and for year, use YEAR() method. Let us first create a table −

mysql> create table DemoTable
(
   StudentName varchar(40),
   StudentAdmissionDate date
);
Query OK, 0 rows affected (0.67 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.10 sec)
mysql> insert into DemoTable values('Robert','2018-09-05');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Mike','2019-09-05');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('David','2019-10-04');
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 −

+-------------+----------------------+
| StudentName | StudentAdmissionDate |
+-------------+----------------------+
| Chris       | 2019-01-21           |
| Robert      | 2018-09-05           |
| Mike        | 2019-09-05           |
| David       | 2019-10-04           |
+-------------+----------------------+
4 rows in set (0.00 sec)

Following is the query to return records with specific month and year −

mysql> select *from DemoTable where month(StudentAdmissionDate)=09 and year(StudentAdmissionDate)=2019;

This will produce the following output −

+-------------+----------------------+
| StudentName | StudentAdmissionDate |
+-------------+----------------------+
| Mike        | 2019-09-05           |
+-------------+----------------------+
1 row in set (0.00 sec)
raja
Published on 07-Oct-2019 10:44:13
Advertisements