Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate time difference in MYSQL

Tags:

mysql

I have Rails application which using MYSQL as database. For some condition, I have to delete all the records from table which was stored exactly 2 hours before the current time.

My query is :

DELETE FROM TABLE_NAME WHERE (NOW() - created_at) > 7200;

Here create_at is datetime column type. Storing the value in the format "2012-12-04 06:39:44"

My problem is, the above query fetch the records even though the record created time is just 40 to 50 minutes and got deleted. The only problem is the record got delete after it reach 40 to 50 minx from it create time.

Can any one please correct my query. I want the MySQL solution. Please help me

like image 664
palani Avatar asked Dec 04 '12 11:12

palani


3 Answers

You probably need this if you want to delete records created exactly 2 hours ago:

DELETE FROM TABLE_NAME WHERE created_at = NOW() - INTERVAL 2 HOUR

or this, that will delete all records created more than 2 hours ago:

DELETE FROM TABLE_NAME WHERE created_at < NOW() - INTERVAL 2 HOUR
like image 153
fthiella Avatar answered Oct 06 '22 19:10

fthiella


Try this ::

DELETE FROM TABLE_NAME WHERE TIMEDIFF(NOW(),created_at) < '02:00:00';
like image 45
Sashi Kant Avatar answered Oct 06 '22 18:10

Sashi Kant


Try:

DELETE FROM TABLE_NAME WHERE created_at<DATE_SUB(NOW(),INTERVAL 2 HOUR)

This query will delete everything created MORE THAN 2 hours ago. Putting an equal sign would mean EXACTLY 2 hours ago (in second). Of course you can format date to consider only minutes, but that would slow down the query. If created_at is indexed (and I think it should be) don't perform any functions on it so it can use index to perform delete faster.

like image 38
Zagor23 Avatar answered Oct 06 '22 20:10

Zagor23