Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Delete all rows older than 10 minutes

Tags:

datetime

mysql

I have a timestamp field in my table. How do I delete records older than 10 minutes old?

Tried this:

DELETE FROM locks WHERE time_created < DATE_SUB( CURRENT_TIME(), INTERVAL 10 MINUTE)

Didn't work. What am I doing wrong?

EDIT: I used this code:

SELECT time_created, CURRENT_TIMESTAMP, TIMESTAMPDIFF( MINUTE, time_created, CURRENT_TIMESTAMP ) FROM locks

But oddly, this gives the wrong result too

time_created         CURRENT_TIMESTAMP      TIMESTAMPDIFF( MINUTE, time_created,     CURRENT_TIMESTAMP )
2010-08-01 11:22:29   2010-08-08 12:00:48   10118
2010-08-01 11:23:03   2010-08-08 12:00:48   10117
like image 607
HyderA Avatar asked Aug 08 '10 07:08

HyderA


2 Answers

If time_created is a unix timestamp (int), you should be able to use something like this:

DELETE FROM locks WHERE time_created < (UNIX_TIMESTAMP() - 600);

(600 seconds = 10 minutes - obviously)

Otherwise (if time_created is mysql timestamp), you could try this:

DELETE FROM locks WHERE time_created < (NOW() - INTERVAL 10 MINUTE)
like image 63
Ivar Bonsaksen Avatar answered Nov 07 '22 09:11

Ivar Bonsaksen


The answer is right in the MYSQL manual itself.

"DELETE FROM `table_name` WHERE `time_col` < ADDDATE(NOW(), INTERVAL -1 HOUR)"
like image 32
Arno Avatar answered Nov 07 '22 09:11

Arno