Select entries with timestamp after X time in MySQL

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable1335
   -> (
   -> ArrivalTime datetime
   -> );
Query OK, 0 rows affected (0.49 sec)

Insert some records in the table using insert command. We have inserted date time records here −

mysql> insert into DemoTable1335 values('2019-09-19 22:54:00');
Query OK, 1 row affected (0.46 sec)
mysql> insert into DemoTable1335 values('2019-09-19 22:59:00');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1335 values('2019-09-19 22:56:00');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1335 values('2019-09-19 22:52:00');
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1335;

This will produce the following output −

+---------------------+
| ArrivalTime         |
+---------------------+
| 2019-09-19 22:54:00 |
| 2019-09-19 22:59:00 |
| 2019-09-19 22:56:00 |
| 2019-09-19 22:52:00 |
+---------------------+
4 rows in set (0.00 sec)

The current date time is as follows −

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2019-09-19 22:55:53 |
+---------------------+
1 row in set (0.00 sec)

Here is the query to select entries with timestamp after X time i.e. 2 minutes here −

mysql> select *from DemoTable1335 where ArrivalTime > date_sub(now(),interval 2 minute);

This will produce the following output −

+---------------------+
| ArrivalTime         |
+---------------------+
| 2019-09-19 22:59:00 |
| 2019-09-19 22:56:00 |
+---------------------+
2 rows in set (0.00 sec)
raja
Published on 05-Nov-2019 06:59:01
Advertisements