100

In my SQL query how do i make it find the records in the last 24 hours? Eg

   SELECT * FROM news WHERE date < 24 hours

I usually do it by setting a variable to date() - 1 day and comparing it to that but I wondered whether the sql query way was faster?

Sebas
  • 21,192
  • 9
  • 55
  • 109
user1022585
  • 13,061
  • 21
  • 55
  • 75

7 Answers7

161

You simply select dates that are higher than the current time minus 1 day.

SELECT * FROM news WHERE date >= now() - INTERVAL 1 DAY;
a'r
  • 35,921
  • 7
  • 66
  • 67
82
SELECT * FROM news WHERE date > DATE_SUB(NOW(), INTERVAL 24 HOUR)
Andrew
  • 26,629
  • 5
  • 63
  • 86
22

To get records from the last 24 hours:

SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR)
GalahadXVI
  • 759
  • 1
  • 8
  • 19
NarayanaReddy
  • 301
  • 2
  • 4
14
SELECT * from new WHERE date < DATE_ADD(now(),interval -1 day);
gdm
  • 7,647
  • 3
  • 41
  • 71
5
SELECT * FROM news WHERE date > DATEADD(d,-1,GETDATE())
Simon
  • 6,062
  • 13
  • 60
  • 97
  • 2
    Never mind, I see you've added that it's MySQL you're using rather than SQL Server. Still, the answer might help someone else :) – Simon Nov 10 '11 at 12:47
  • To substract 1 day from current date has not the same result as to select a 24 hour intervall, which was the relevant question. The timeframe after substract 1 yay from GETDATE() has in maximum a timeframe of 47.99 hours – termigrator Jan 13 '20 at 07:16
3

There are so many ways to do this. The listed ones work great, but here's 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 the mistake of comparing it to 86400 (number of seconds in a day), or your output will be all kinds of wrong.

Taryn
  • 242,637
  • 56
  • 362
  • 405
Craig Labenz
  • 2,489
  • 3
  • 22
  • 17
  • 1
    You may wish to use < maketime(24,00,00). I noticed the behavior of the original query is inconsistent. –  Jan 22 '15 at 19:09
-2
SELECT * FROM news WHERE date < DATEADD(Day, -1, date)
Lasse Edsvik
  • 9,070
  • 16
  • 73
  • 109