Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows that are less than 5 minutes old using DATE_SUB

I have a table that is getting hundreds of requests per minute. The issue that I'm having is that I need a way to select only the rows that have been inserted in the past 5 minutes. I am trying this:

SELECT count(id) as count, field1, field2
FROM table
WHERE timestamp > DATE_SUB(NOW(), INTERVAL 5 MINUTE)
ORDER BY timestamp DESC

My issue is that it returns 70k+ results and counting. I am not sure what it is that I am doing wrong, but I would love to get some help on this. In addition, if there were a way to group them by minute to have it look like:

| count | field1 | field2 | 
----------------------------

I'd love the help and direction on this, so please let me know your thoughts.

like image 706
Tom Sampson Avatar asked Feb 02 '12 03:02

Tom Sampson


1 Answers

You don't really need DATE_ADD/DATE_SUB, date arithmetic is much simpler:

SELECT COUNT(id), DATE_FORMAT(`timestamp`, '%Y-%m-%d %H:%i')
FROM `table`
WHERE `timestamp` >= CURRENT_TIMESTAMP - INTERVAL 5 MINUTE
GROUP BY 2
ORDER BY 2
like image 93
Salman A Avatar answered Oct 12 '22 12:10

Salman A