MySQL query to select closest date from today?



Let’s say the current date is 2019-07-25. We will now see an example and create a table where ShippingDate is added in the table.

Let us first create a table −

mysql> create table DemoTable667(ShippingDate datetime); Query OK, 0 rows affected (0.46 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable667 values('2019-01-31'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable667 values('2019-07-19'); Query OK, 1 row affected (0.69 sec) mysql> insert into DemoTable667 values('2019-07-23'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable667 values('2019-08-24'); Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable667;

This will produce the following output −

+---------------------+ | ShippingDate       | +---------------------+ | 2019-01-31 00:00:00 | | 2019-07-19 00:00:00 | | 2019-07-23 00:00:00 | | 2019-08-24 00:00:00 | +---------------------+ 4 rows in set (0.00 sec)

Following is the query to get the closest date from today −

mysql> select ShippingDate    from DemoTable667    where date(ShippingDate) = (select min(date(ShippingDate))       from DemoTable667       where date(ShippingDate) > date(now())    );

This will produce the following output −

+---------------------+ | ShippingDate       | +---------------------+ | 2019-07-23 00:00:00 | +---------------------+ 1 row in set (0.00 sec)
Updated on: 2019-08-23T13:19:44+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements