MySQL query to select records approaching in next 12 hours?

MySQLMySQLi Database

For this, you can use INTERVAL 12 hour using DATE_ADD(). Let us first create a table −

mysql> create table DemoTable (DueDateTime datetime);
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('2019-07-12 10:50:30');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable values('2019-07-12 22:02:00');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('2019-07-12 11:12:10');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('2019-07-12 09:02:00');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+---------------------+
| DueDateTime         |
+---------------------+
| 2019-07-12 10:50:30 |
| 2019-07-12 22:02:00 |
| 2019-07-12 11:12:10 |
| 2019-07-12 09:02:00 |
+---------------------+
4 rows in set (0.00 sec)

Following is the query to select records approaching in next 12 hours −

mysql> select *from DemoTable where date_add(DueDateTime,interval 12 hour) BETWEEN NOW() AND
DATE_ADD(NOW(), INTERVAL 12 HOUR);

This will produce the following output −

+---------------------+
| DueDateTime         |
+---------------------+
| 2019-07-12 10:50:30 |
| 2019-07-12 22:02:00 |
| 2019-07-12 11:12:10 |
+---------------------+
3 rows in set (0.00 sec)
raja
Published on 22-Aug-2019 15:02:13
Advertisements