How to select all records that are 10 minutes within current timestamp in MySQL?
Your question asks for records within 10 minutes of the current timestamp, but I will take that to mean no more than ten minutes in the past (not the future):
SELECT col1, col2, col3
FROM table
WHERE DATE_ADD(last_seen, INTERVAL 10 MINUTE) >= NOW();
This adds 10 minutes to last_seen
and compares that against the current time. If the value is greater, last_seen
is less than ten minutes ago.
See the documentation on DATE_ADD()
for an explanation of how it is used.
The most efficient way would be to compare your timestamp (and only timestamp, without using any functions on it) to an expression that can be calculated as constant for every row, this way mysql can use index defined on your timestamp column.
SELECT * FROM myTable
WHERE last_seen >= NOW() - INTERVAL 10 MINUTE
You can always try EXPLAIN SELECT ...
to see if an index can be used to find rows satisfying your WHERE condition without the need to check every row in the table.
In case the method didn't work for some.
The 'where' condition in answers above didn't work for me until i added the timestamp column inside date() function (suggested by @karam qubsi) :
SELECT * FROM myTable
WHERE date(last_seen) >= NOW() - INTERVAL 10 MINUTE
Only then i started getting correct results.