Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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-25'

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

thanks

like image 650
Michael Avatar asked May 07 '12 13:05

Michael


People also ask

Can you compare timestamp with date in SQL?

A date, time, or timestamp value can be compared with another value of the same data type, a datetime constant of the same data type, or with a string representation of a value of that data type. Additionally, a TIMESTAMP WITHOUT TIME ZONE value can be compared with a TIMESTAMP WITH TIME ZONE value.

How do I select a date from a timestamp in SQL?

In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column. (In our example, we use a column of the timestamp data type.)

How do I do a timestamp in SQL?

MySQL TIMESTAMP() FunctionThe TIMESTAMP() function returns a datetime value based on a date or datetime value. Note: If there are specified two arguments with this function, it first adds the second argument to the first, and then returns a datetime value.

What is timestamp format in SQL?

SQL Date Data Types TIMESTAMP - format: YYYY-MM-DD HH:MI:SS.


3 Answers

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

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

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-25 00:00:00' AND '2012-05-25 23:59:59'
like image 111
Marcus Adams Avatar answered Oct 23 '22 08:10

Marcus Adams


 WHERE cast(timestamp as date) = '2012-05-05'
like image 11
juergen d Avatar answered Oct 23 '22 08:10

juergen d


As suggested by some, by using DATE(timestamp) you are applying manipulation to the column and therefore you cannot rely on the index ordering.

However, using BETWEEN would only be reliable if you include the milliseconds. In the example timestamp BETWEEN '2012-05-05 00:00:00' AND '2012-05-05 23:59:59' you exclude records with a timestamp between 2012-05-05 23:59:59.001 and 2012-05-05 23:59:59.999. However, even this method has some problems, because of the datatypes precision. Occasionally 999 milliseconds is rounded up.

The best thing to do is:

SELECT * FROM table
WHERE date>='2012-05-05' AND date<'2012-05-06'
like image 10
Tom Kitson Avatar answered Oct 23 '22 09:10

Tom Kitson