Ignoring the year in MySQL Query with date range?

MySQLMySQLi Database

To ignore the year with date range, use the DATE_FORMAT() with the between clause. Let us first create a demo table. The query to create a table is as follows −

mysql> create table igonreYearDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ShippingDate date
   -> );
Query OK, 0 rows affected (0.75 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into igonreYearDemo(ShippingDate) values('2016-01-31');
Query OK, 1 row affected (0.16 sec)
mysql> insert into igonreYearDemo(ShippingDate) values('2018-01-31');
Query OK, 1 row affected (0.13 sec)
mysql> insert into igonreYearDemo(ShippingDate) values('2015-06-23');
Query OK, 1 row affected (0.17 sec)
mysql> insert into igonreYearDemo(ShippingDate) values('2015-06-23');
Query OK, 1 row affected (0.15 sec)
mysql> insert into igonreYearDemo(ShippingDate) values('2014-02-01');
Query OK, 1 row affected (0.20 sec)
mysql> insert into igonreYearDemo(ShippingDate) values('2019-01-31');
Query OK, 1 row affected (0.16 sec)
mysql> insert into igonreYearDemo(ShippingDate) values('2019-02-14');
Query OK, 1 row affected (0.11 sec)
mysql> insert into igonreYearDemo(ShippingDate) values('2019-03-12');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from igonreYearDemo;

Here is the output −

+----+--------------+
| Id | ShippingDate |
+----+--------------+
| 1  | 2016-01-31   |
| 2  | 2018-01-31   |
| 3  | 2015-06-23   |
| 4  | 2015-06-23   |
| 5  | 2014-02-01   |
| 6  | 2019-01-31   |
| 7  | 2019-02-14   |
| 8  | 2019-03-12   |
+----+--------------+
8 rows in set (0.00 sec)

The following is the query to ignore year with date range −

mysql> select *from igonreYearDemo tbl where DATE_FORMAT(tbl.ShippingDate, '%m-%d') between '01-01' and '03-31';

Here is the output −

+----+--------------+
| Id | ShippingDate |
+----+--------------+
| 1  | 2016-01-31   |
| 2  | 2018-01-31   |
| 5  | 2014-02-01   |
| 6  | 2019-01-31   |
| 7  | 2019-02-14   |
| 8  | 2019-03-12   |
+----+--------------+
6 rows in set (0.00 sec)
raja
Published on 01-Apr-2019 12:08:57
Advertisements