lunes, 25 de enero de 2016

How to select records from last 24 hours using SQL?

I am looking for a where clause that can be used to retrieve records for the last 24 hours?
shareimprove this question
1 
Do you have a timestamp field on these records? – Shawn Steward Dec 11 '09 at 14:52

8 Answers

up vote45down voteaccepted
SELECT * 
FROM table_name
WHERE table_name.the_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
shareimprove this answer
1 
If the records are stored as DATETIME, this will select all records from the previous date, disregarding the time part. Been run at 23:59:59, the query will return all records for the last 48 hours, not 24. – Quassnoi Dec 11 '09 at 15:02
8 
If you want to select the last 24 hours from a datetime field, substitute 'curate()' with 'now()'. This also includes the time. – Haentz Apr 30 '11 at 6:11 
In MySQL:
SELECT  *
FROM    mytable
WHERE   record_date >= CURDATE() - INTERVAL 1 DAY
In SQL Server:
SELECT  *
FROM    mytable
WHERE   record_date >= DATEADD(day, -1, GETDATE())
In Oracle:
SELECT  *
FROM    mytable
WHERE   record_date >= SYSDATE - 1
In PostgreSQL:
SELECT  *
FROM    mytable
WHERE   record_date >= NOW() - '1 day'::INTERVAL
In Redshift:
SELECT  *
FROM    mytable
WHERE   record_date >= GETDATE() - '1 day'::INTERVAL
In SQLite:
SELECT  *
FROM    mytable
WHERE   record_date >= datetime('now','-1 day')
In MS Access:
SELECT  *
FROM    mytable
WHERE   record_date >= (Now - 1)
shareimprove this answer
   
I try the query for mysql but if its 2AM, for example, i get the records from 00 - 02 AM. Two hours only instead of 24. Any ideas? – John Jul 15 '14 at 22:36
   
I very much like the solution provided here, just what I noted in MySQL is the performance of Guillaume Flandre solution was faster. – oneworld Jul 31 '14 at 0:36
   
Perfect answer! – Bertie Jul 23 '15 at 8:52
MySQL :
SELECT * 
FROM table_name
WHERE table_name.the_date > DATE_SUB(NOW(), INTERVAL 24 HOUR)
The INTERVAL can be in YEAR, MONTH, DAY, HOUR, MINUTE, SECOND
For example, In the last 10 minutes
SELECT * 
FROM table_name
WHERE table_name.the_date > DATE_SUB(NOW(), INTERVAL 10 MINUTE)
shareimprove this answer
Which SQL was not specified, SQL 2005 / 2008
SELECT yourfields from yourTable WHERE yourfieldWithDate > dateadd(dd,-1,getdate())
If you are on the 2008 increased accuracy date types, then use the new sysdatetime() function instead, equally if using UTC times internally swap to the UTC calls.
shareimprove this answer
in postgres, assuming your field type is a timestamp:
select * from table where date_field > (now() - interval '24 hour');
shareimprove this answer
select ...
from ...
where YourDateColumn >= getdate()-1
shareimprove this answer
SELECT * 
FROM tableName 
WHERE datecolumn >= dateadd(hour,-24,getdate())
shareimprove this answer
In SQL Server (For last 24 hours):
SELECT  *
FROM    mytable
WHERE   order_date > DateAdd(DAY, -1, GETDATE()) and order_date<=GETDATE()

No hay comentarios:

Publicar un comentario