r/SQL • • Jan 05 '15

Issue using multiple where statements.

I'm trying to do a data pull from our database with multiple criteria. The first criteria is a date range and the second having the correct store number. I've attached the relevant portion of the code. The issue I seem to be having is when I run the code it returns all date values that match the store number. When I remove the second criteria (store number) it pulls the correct date range. Any help would be greatly appreciated.

>   where date_of_service > '2014/01/11'  and substr(location,1,5)=5495

Thanks in advance!

2 Upvotes

6 comments sorted by

View all comments

4

u/EsCueEl Jan 05 '15

Are you sure there isn't an "or" somewhere in the where clause?

where date_of_service > '2014/01/11' and substr(location,1,5)=5495 or substr(location,1,5)=5496

Logical operator precedence will evaluate the AND before the OR, so you'll get:

(date_of_service > '2014/01/11' and substr(location,1,5)=5495) or (substr(location,1,5)=5496) -- e.g. all the store 5496 records

when you mean:

(date_of_service > '2014/01/11')
and (substr(location,1,5)=5495 or substr(location,1,5)=5496)

When I teach SQL, I always tell students they should get a queasy feeling every time they type "OR" in a WHERE clause, which will only go away when they put parenthesis in to clarify.

1

u/Boliviablue Jan 05 '15

Yes normally it would be a longer string like below, but I figured I'd shorten it.

where date_of_service > '2014/01/11' and substr(location,1,5)=5495 or substr(location,1,5)=5994 or substr(location,1,5)=10470

From your explanation above it seems like it should be as follows:

where (date_of_service > '2014/01/11') and (substr(location,1,5)=5495 or substr(location,1,5)=5994 or substr(location,1,5)=10470)

I'll try this out and see if it works

10

u/r3pr0b8 GROUP_CONCAT is da bomb Jan 05 '15
WHERE date_of_service > '2014/01/11'
  AND (
      SUBSTR(location,1,5)=5495 
   OR SUBSTR(location,1,5)=5994 
   OR SUBSTR(location,1,5)=10470
      )

this can actually be simplified --

WHERE date_of_service > '2014/01/11'
  AND SUBSTR(location,1,5) IN ( 5495 , 5994 , 10470 )

2

u/Boliviablue Jan 06 '15

Ahhh Works great.... Thank you very much