Search for records with a date field in the last 24 hours

In my SQL query, how can I find records in the last 24 hours? For example,

SELECT * FROM news WHERE date < 24 hours 

I usually do this by setting the date () variable to 1 day and comparing it with this, but I wondered if the sql query was faster?

+75
date sql mysql
Nov 10 '11 at 12:41
source share
7 answers

You simply select dates that exceed the current time minus 1 day.

 SELECT * FROM news WHERE date >= now() - INTERVAL 1 DAY; 
+119
Nov 10 '11 at 12:48
source share
 SELECT * FROM news WHERE date > DATE_SUB(NOW(), INTERVAL 24 HOUR) 
+62
Nov 10 '11 at
source share
 SELECT * from new WHERE date < DATE_ADD(now(),interval -1 day); 
+9
Dec 18 '14 at
source share

To get records in the last 24 hours:

 SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR) 
+7
Sep 09 '14 at 7:21
source share
 SELECT * FROM news WHERE date > DATEADD(d,-1,GETDATE()) 
+3
Nov 10 '11 at 12:45
source share

There are so many ways to do this. The above works fine, but here is another way if you have a datetime field:

 SELECT [fields] FROM [table] WHERE timediff(now(), my_datetime_field) < '24:00:00' 

timediff() returns a time object, so don't make a mistake comparing it to 86400 (number of seconds per day), or your result will be all kinds of.

+3
Jun 28 '12 at 13:40
source share
 SELECT * FROM news WHERE date < DATEADD(Day, -1, date) 
-3
Nov 10 '11 at 12:43
source share



All Articles