Delete records where timestamp older than 5 minutes in MySQL?


For this, use DELETE command. Let us first create a table −

mysql> create table DemoTable1851
     (
     DueDate datetime
     );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1851 values('2019-12-03 21:30:35');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1851 values('2019-12-03 21:45:00');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1851 values('2019-12-03 21:34:00');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1851;

This will produce the following output −

+---------------------+
| DueDate             |
+---------------------+
| 2019-12-03 21:30:35 |
| 2019-12-03 21:45:00 |
| 2019-12-03 21:34:00 |
+---------------------+
3 rows in set (0.00 sec)

The current date time is as follows −

mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2019-12-03 21:38:46 |
+---------------------+
1 row in set (0.00 sec)

Here is the query to delete records where timestamp is older than 5 minutes −

mysql> delete from DemoTable1851 where DueDate < (NOW() - INTERVAL 5 MINUTE);
Query OK, 2 rows affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1851;

This will produce the following output −

+---------------------+
| DueDate             |
+---------------------+
| 2019-12-03 21:45:00 |
+---------------------+
1 row in set (0.00 sec)

Updated on: 26-Dec-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements