Reputation: 33946
I'm trying to select rows from the last 2 hours. For some reason it doesn't work. The code syntax looks ok and works when used on other tables, but for some reason when used on table Posts
, get rows a lot older than 2 hours.
SELECT * FROM Posts WHERE `Date` > SUBDATE( CURRENT_DATE, INTERVAL 2 HOUR)
Is there any problem with the code? Is there another way to write it? What could be the reason for this?
Upvotes: 14
Views: 21976
Reputation: 139
none of the answers above worked for me, try this:
SELECT * FROM POSTS WHERE DATE > DATEADD(HH, (-2), GETDATE())
Upvotes: 0
Reputation: 4767
You can try this one
SELECT * FROM Posts WHERE `Date` > DATE_SUB(CURDATE(), INTERVAL 3 HOUR)
Upvotes: 1
Reputation: 16223
That's because you're using CURRENT_DATE
, you should use NOW()
or CURRENT_TIMESTAMP
instead.
The problem is that using CURRENT_DATE
, being a date value, the time defaults to 00:00:00
, so by substracting 2 hours you end up getting 22:00:00
of the previous day, instead of the last 2 hours...
Upvotes: 9
Reputation: 41408
You can use simpler notation:
SELECT * FROM Posts WHERE `Date` > NOW() - INTERVAL 2 HOUR
Upvotes: 24
Reputation: 9794
change to this:
SELECT * FROM Posts WHERE `Date` > SUBDATE( CURRENT_TIMESTAMP, INTERVAL 2 HOUR)
Upvotes: 6