How can fetch records from specific month and year in a MySQL table?

MySQLMySQLi Database

Use YEAR() and MONTH() to display records from specific month and year respectively. Let us first create a table −

mysql> create table DemoTable
   (
   CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   CustomerName varchar(20),
   CustomerTotalBill int,
   PurchasingDate date
   );
Query OK, 0 rows affected (0.83 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('John',2000,'2019-01-21');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Chris',1000,'2019-01-31');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Robert',4500,'2018-01-01');
Query OK, 1 row affected (0.24 sec)

mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Sam',5500,'2017-02-12');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable(CustomerName,CustomerTotalBill,PurchasingDate) values('Carol',500,'2016-01-12');
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 −

+------------+--------------+-------------------+----------------+
| CustomerId | CustomerName | CustomerTotalBill | PurchasingDate |
+------------+--------------+-------------------+----------------+
| 1          | John         | 2000              | 2019-01-21     |
| 2          | Chris        | 1000              | 2019-01-31     |
| 3          | Robert       | 4500              | 2018-01-01     |
| 4          | Sam          | 5500              | 2017-02-12     |
| 5          | Carol        | 500               | 2016-01-12     |
+------------+--------------+-------------------+----------------+
5 rows in set (0.00 sec)

Following is the query to display records from specific month and year in MySQL −

mysql> select *from DemoTable WHERE YEAR(DATE(PurchasingDate))=2019 AND MONTH(DATE(PurchasingDate)) = 01;

This will produce the following output −

+------------+--------------+-------------------+----------------+
| CustomerId | CustomerName | CustomerTotalBill | PurchasingDate |
+------------+--------------+-------------------+----------------+
| 1          | John         | 2000              | 2019-01-21     |
| 2          | Chris        | 1000              | 2019-01-31     |
+------------+--------------+-------------------+----------------+
2 rows in set (0.03 sec)
raja
Published on 21-May-2019 11:45:37
Advertisements