How to compare timestamp dates with date-only parameter in MySQL?

Michael picture Michael · May 7, 2012 · Viewed 178.2k times · Source

In a SQL statement, how do I compare a date saved as TIMESTAMP with a date in YYYY-MM-DD format?

Ex.: SELECT * FROM table WHERE timestamp = '2012-05-05'

I want this query returns all rows having timestamp in the specified day, but it returns only rows having midnight timestamp.

thanks

Answer

Marcus Adams picture Marcus Adams · May 7, 2012

You can use the DATE() function to extract the date portion of the timestamp:

SELECT * FROM table
WHERE DATE(timestamp) = '2012-05-05'

Though, if you have an index on the timestamp column, this would be faster because it could utilize an index on the timestamp column if you have one:

SELECT * FROM table
WHERE timestamp BETWEEN '2012-05-05 00:00:00' AND '2012-05-05 23:59:59'