I am trying to count the rows in a table in my database that were inserted within X hours or X days. I have tried repeatedly but I keep getting empty set responses.
Rather than selecting rows where start_stamp
is equal to now() - 1day
, you need rows where it is greater than or equal to that range. Additionally, your syntax is a little off. MySQL's date arithmetic uses column_value - INTERVAL <number> <period>
, so you need:
SELECT COUNT(*) AS num_new_rows
FROM mytable
WHERE start_stamp >= NOW() - INTERVAL 1 DAY
Likewise to get n hours ago, use INTERVAL n HOUR
# Within 3 hours...
WHERE start_stamp >= NOW() - INTERVAL 3 HOUR
The syntax for date interval arithmetic is described in a small paragraph beneath the DATE_ADD() function reference in the official MySQL documentation.
Here are a some examples...
All entries within the past 6 hours:
select * from mytable where start_stamp >= now() - interval 6 hour;
All entries within the past 2 days:
select * from mytable where start_stamp >= now() - interval 2 day;
All entries within the past 2 1/2 days:
select * from mytable where start_stamp >= now() - interval 2 day - interval 12 hour;