I have a column of type "datetime" with values like 2009-10-20 10:00:00
I would like to extract date from datetime and write a query like:
SELECT * FROM
data
WHERE datetime = '2009-10-20'
ORDER BY datetime DESC
Is the following the best way to do it?
SELECT * FROM
data
WHERE datetime BETWEEN('2009-10-20 00:00:00' AND '2009-10-20 23:59:59')
ORDER BY datetime DESC
This however returns an empty resultset. Any suggestions?
Here are all formats
Say this is the column that contains the
datetime
value, tabledata
.You can use:
Or:
Or:
Well, using like in statement is the best option where datetime like '2009-10-20%' , it should work in this case
simple and best way to use date function
example
OR
You can use MySQL's
DATE()
function:You could also try this:
WHERE datetime LIKE '2009-10-20%'
See this answer for info on the performance implications of using
LIKE
.Using
WHERE DATE(datetime) = '2009-10-20'
has performance issues. As stated here:DATE()
for all rows, including those, that don't matchUse
BETWEEN
or>
,<
,=
operators which allow to use an index:Update: the impact on using
LIKE
instead of operators in an indexed column is high. These are some test results on a table with 1,176,000 rows:datetime LIKE '2009-10-20%'
=> 2931msdatetime >= '2009-10-20 00:00:00' AND datetime <= '2009-10-20 23:59:59'
=> 168msWhen doing a second call over the same query the difference is even higher: 2984ms vs 7ms (yes, just 7 milliseconds!). I found this while rewriting some old code on a project using Hibernate.