Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query selecting between two dates

Tags:

sql

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'
like image 973
Rory Lester Avatar asked Dec 03 '25 02:12

Rory Lester


2 Answers

I would suggest converting the dates to a datetime and comparing them as well as keeping the date standard and consistent. Something like:

"SELECT * 
FROM house 
WHERE DATE(startDate) >= DATE('2012-02-22 00:00:00') 
  AND DATE(endDate) <= DATE('2012-02-25 00:00:00')"

NOTE: I assumed your startDate and endDate were of the same format as the strings your provided.

like image 138
northpole Avatar answered Dec 05 '25 17:12

northpole


Do you want all rows that startDate is '2012-02-22' or later and endDate is '2012-02-22' or previous? Then, use this:

SELECT * 
FROM house 
WHERE startDate >= '2012-02-22' 
  AND endDate < '2012-02-26'           --- notice the `<`, not `<=`
                                       --- and the `day+1`

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 than Year-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, use endDate < '2012-02-26' instead.

You could use DATE(endDate) <= DATE('2012-02-25 00:00:00') or DATE(endDate) <= '2012-02-25' but these conditions are "un-sargable", so your queries will not be able to use an index on endDate.

like image 41
ypercubeᵀᴹ Avatar answered Dec 05 '25 17:12

ypercubeᵀᴹ