I want to select records between two dates - a startDate and endDate (they are date/time format in sql). I have the following sql query but it does not work, could someone tell me what I'm doing wrong?
"SELECT *
FROM house
WHERE startDate >= '2012/02/22 00:00:00' AND endDate <= '2012-02-25 00:00:00'"
There is the builtin
STR_TO_DATE
function in MySql that takes same format mask as date_format.I would suggest converting the dates to a datetime and comparing them as well as keeping the date standard and consistent. Something like:
NOTE: I assumed your startDate and endDate were of the same format as the strings your provided.
Do you want all rows that
startDate
is'2012-02-22'
or later andendDate
is'2012-02-22'
or previous? Then, use this:When using dates with SQL products, better use this format in queries and statements:
'20120222'
or this (which I find easier to read:'2012-02-22'
.Using slashes like
'2012/02/22'
or any other order thanYear-Month-Day
is not recommended.There's no need to include the time part.
'2012-02-22 00:00:00'
is the same as'2012-02-22'
.Using
endDate <= '2012-02-25 00:00:00'
means that any row with date 25nd of Feb. 2012 but time after midnight ('00:00:00'
) will not match the condition. If you want those rows, too, useendDate < '2012-02-26'
instead.You could use
DATE(endDate) <= DATE('2012-02-25 00:00:00')
orDATE(endDate) <= '2012-02-25'
but these conditions are "un-sargable", so your queries will not be able to use an index onendDate
.