Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select records with date in the last 24 hours

Tags:

select

mysql

I want to select from my table all records where date (datetime mysql format YYYY-MM-DD HH:MM:SS) is in the last 24 hours. I have a query, but it doesn't completely work

 SELECT * FROM `my_table` WHERE date > DATE_SUB(NOW(), INTERVAL 24 HOUR)

why it returns the date like that 2013-07-01 12:00:00. How would I do this? Thanks.

like image 611
Indy Avatar asked Jun 28 '13 14:06

Indy


People also ask

How do I get only the latest record by datetime in SQL?

if you need by other column datetime then you can use ->orderBy('columnName','desc/asc')->get() otherwise you can use latest() function.

How do I get last hour data in SQL?

Here is the SQL to show latest time using now() function. Here is the SQL to get last 1 hour data in MySQL. In the above query, we select only those rows whose order_date falls within past 1 hour interval. We use INTERVAL clause to easily substract 1 hour interval from present time obtained using now() function.


1 Answers

You already have a lower limit on the date, but since your table can have future dates you also need an upper limit. This should work:

SELECT *
FROM my_table
WHERE date > DATE_SUB(NOW(), INTERVAL 24 HOUR)
  AND date <= NOW()
like image 115
Ed Gibbs Avatar answered Nov 15 '22 20:11

Ed Gibbs