Select records from NOW() -1 Day
Asked Answered
U

7

231

Is there a way in a MySQL statement to order records (through a date stamp) by >= NOW() -1 so all records from the day before today to the future are selected?

Unattended answered 17/12, 2011 at 11:35 Comment(0)
S
429

Judging by the documentation for date/time functions, you should be able to do something like:

SELECT * FROM FOO
WHERE MY_DATE_FIELD >= NOW() - INTERVAL 1 DAY
Sappanwood answered 17/12, 2011 at 11:39 Comment(3)
how to get now to so on.. mean current date to all records those are available in db. ? this is just for one day but i need all record now to on words. @jonPerilous
Does it consider the user's localtime when the records are in UTC?Coeducation
@Adry: I doubt it, but you should test carefully.Sappanwood
N
83

Be aware that the result may be slightly different than you expect.

NOW() returns a DATETIME.

And INTERVAL works as named, e.g. INTERVAL 1 DAY = 24 hours.

So if your script is cron'd to run at 03:00, it will miss the first three hours of records from the 'oldest' day.

To get the whole day use CURDATE() - INTERVAL 1 DAY. This will get back to the beginning of the previous day regardless of when the script is run.

Nirvana answered 6/6, 2014 at 17:16 Comment(0)
M
28

Didn't see any answers correctly using DATE_ADD or DATE_SUB:

Subtract 1 day from NOW()

...WHERE DATE_FIELD >= DATE_SUB(NOW(), INTERVAL 1 DAY)

Add 1 day from NOW()

...WHERE DATE_FIELD >= DATE_ADD(NOW(), INTERVAL 1 DAY)
Monicamonie answered 3/8, 2018 at 13:48 Comment(1)
Looks "cleaner", somehow, but a bit "heavy" as well. Is there really any added value in explicitly calling a method rather than using a simple addition/substraction ?Barracuda
T
24

You're almost there: it's NOW() - INTERVAL 1 DAY

Trixi answered 17/12, 2011 at 11:40 Comment(0)
S
8

Sure you can:

SELECT * FROM table
WHERE DateStamp > DATE_ADD(NOW(), INTERVAL -1 DAY)
Sandbox answered 17/12, 2011 at 11:43 Comment(1)
Confusing using DATE_ADD then -1 day.Monicamonie
C
1

when search field is timestamp and you want find records from 0 hours yesterday and 0 hour today use construction

MY_DATE_TIME_FIELD between makedate(year(now()), date_format(now(),'%j')-1) and makedate(year(now()), date_format(now(),'%j'))  

instead

 now() - interval 1 day
Cookgeneral answered 20/7, 2016 at 8:15 Comment(0)
R
0

try this: SELECT * FROM FOO WHERE MY_DATE_FIELD >= NOW() - INTERVAL '1' DAY

Representational answered 4/4, 2023 at 6:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.