0

I have three date columns in a db row. The columns are independent of each other in that any of them can either be populated or NULL.

I'd like to check to find all rows where any of the date columns fall within a known range.

This is what I have in my WHERE clause:

WHERE (d.date1 OR d.date2 OR d.date3) 
    BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46'

Any ideas as to why this isn't working would be appreciated.

Many thanks

1
  • Just out of curiosity, how would you select where column A or column B have the value 2? "where (A or B) = 2" or "where A = 2 or B = 2"? Commented Jun 4, 2013 at 13:31

4 Answers 4

1

You are misunderstanding how logical "OR" works.

WHERE (d.date1 BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46') 
   OR (d.date2 BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46') 
   OR (d.date3 BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46')
Sign up to request clarification or add additional context in comments.

Comments

0

You have to specify the three parts separately.

Note that (d.date1 OR d.date2 OR d.date3) will evaluate to true if any of the dates have a value, so your WHERE clause is currently the equivalent of this:

WHERE TRUE BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46'

So you'll need to test each date separately:

WHERE d.date1 BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46'
   OR d.date2 BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46'
   OR d.date3 BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46'

1 Comment

Great, thanks very much! This makes sense. However my the code I'm working with only allows me to use each of the known date variables once. So whilst the above is a logical outcome, I can't use it. I need some way of comparing each date against the range but only declaring the date range once. Thanks again.
0

You should be doing it like this:

WHERE (d.date1 BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46')
OR (d.date2 BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46')
OR (d.date3 BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46')

Comments

0

Because Between operator needs a single value to the left of Between. Reverse the sequence... like this:

WHERE d.date1 BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46' Or
      d.date2 BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46' Or
      d.date3 BETWEEN '2011-11-09 13:08:46' AND '2011-11-11 16:08:46'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.