MySQL query to get next closest day between two days?


Following is the syntax −

select * from yourTableName
order by ( yourColumnName> now()) desc, (case when yourColumnName > now() then yourColumnName end) ,
   yourColumnName  desc
limit 1;

Let us first create a table −

mysql> create table DemoTable1454
   -> (
   -> ShippingDate date
   -> );
Query OK, 0 rows affected (0.59 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1454 values('2019-10-01');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable1454 values('2019-10-03');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable1454 values('2019-10-05');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable1454 values('2019-10-04');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable1454 values('2018-10-06');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1454 values('2019-10-06');
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1454;

This will produce the following output −

+--------------+
| ShippingDate |
+--------------+
| 2019-10-01   |
| 2019-10-03   |
| 2019-10-05   |
| 2019-10-04   |
| 2018-10-06   |
| 2019-10-06   |
+--------------+
6 rows in set (0.00 sec)

The current date is as follows −

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2019-10-04 21:30:01 |
+---------------------+
1 row in set (0.00 sec)

Here is the query to get next closest day between two days −

mysql> select * from DemoTable1454
   -> order by ( ShippingDate > now()) desc,
   ->    (case when ShippingDate > now() then ShippingDate  end) ,
   ->    ShippingDate  desc
   -> limit 1;

This will produce the following output −

+--------------+
| ShippingDate |
+--------------+
| 2019-10-05   |
+--------------+
1 row in set (0.00 sec)

Updated on: 10-Dec-2019

84 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements