Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL WHERE query on date range

In my table I have 118 records detailing projects. The 2 fields I am concerned with here are startdate and enddate.

I need to produce a report from this view which shows which projects were 'active' between the following date ranges:

01/01/2011 - 01/12/2011

I have tried the following WHERE clase:

WHERE startdate BETWEEN '01/04/2011' AND '01/12/2011' 
OR enddate BETWEEN '01/04/2011' AND '01/12/2011'
OR startdate <= '01/04/2011' AND enddate >= '01/12/2011'

What comes through does not seem correct, there are only a few records displayed and many which I know for a fact should be displayed are not, such as one project with a start date of 20/07/2011 and enddate of 21/11/2011 dissapears when the WHERE query is run.

Can anyone see a fault with this WHERE query

enter image description here

like image 960
JsonStatham Avatar asked Aug 24 '26 13:08

JsonStatham


1 Answers

WHERE
    startdate <= '2011-12-01'
AND enddate   >= '2011-01-01'

(Assuming the value in enddate is the last date the project is active)

Examples using numbers, searching for anything that overlaps 100 to 200...

Start | End | Start <= 200 | End >= 100

 000  | 099 |  Yes         | No
 101  | 199 |  Yes         | Yes     (HIT!)
 201  | 299 |  No          | Yes
 000  | 150 |  Yes         | Yes     (HIT!)
 150  | 300 |  Yes         | Yes     (HIT!)
 000  | 300 |  Yes         | Yes     (HIT!)

This absolutely needs an AND in the logic :)


In terms of your query...

Your query with parenthesis, looks like this...

WHERE
  (
     startdate BETWEEN '01/04/2011' AND '01/12/2011'
  OR enddate   BETWEEN '01/04/2011' AND '01/12/2011'
  OR startdate <= '01/04/2011'
  )
  AND enddate >= '01/12/2011'

But your example never meets the last AND condition. Try adding parenthesis to be more explicit...

WHERE
     (startdate BETWEEN '01/04/2011' AND '01/12/2011')
  OR (enddate   BETWEEN '01/04/2011' AND '01/12/2011')
  OR (startdate <= '01/04/2011' AND enddate >= '01/12/2011')
like image 73
MatBailie Avatar answered Aug 27 '26 05:08

MatBailie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!