MySQL query to fetch records from a range of months?


Let us first create a table −

mysql> create table DemoTable1795
     (
     Name varchar(20),
     DueDate date
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1795 values('John','2018-07-21');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1795 values('Sam','2019-10-21');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1795 values('Sam','2019-01-10');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1795 values('Mike','2018-12-31');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1795;

This will produce the following output −

+------+------------+
| Name | DueDate    |
+------+------------+
| John | 2018-07-21 |
| Sam  | 2019-10-21 |
| Sam  | 2019-01-10 |
| Mike | 2018-12-31 |
+------+------------+
4 rows in set (0.00 sec)

Here is the query to get records from a range of months −

mysql> select * from DemoTable1795
     where (YEAR(DueDate) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))
         AND MONTH(DueDate) BETWEEN 7 AND 12)
     OR (YEAR(DueDate) = YEAR(CURRENT_DATE())
         AND MONTH(DueDate) BETWEEN 1 AND 7);

This will produce the following output −

+------+------------+
| Name | DueDate    |
+------+------------+
| John | 2018-07-21 |
| Sam  | 2019-01-10 |
| Mike | 2018-12-31 |
+------+------------+
3 rows in set (0.00 sec)

Updated on: 25-Feb-2020

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements