'SQL QUERY CLAUS WHERE

I have this where clause

WHERE        (ACCDAT_0 >= '2020-01-01 00:00:00.000')and STA_0='3'
and
(NUM_0 LIKE '%FTC%') OR (NUM_0 LIKE '%NCC%') OR (NUM_0 LIKE '%DCF%')

The point is that if STA_0='1' is appearing in the query because its like NCC it possible to appear all NCC except the ones where the flag is 1?



Solution 1:[1]

This is really a comment, but it's too large to fit in the comment space... elaboration on my comment above.

"OR" is a low precedence operator, meaning it is evaluated after all "AND." What this means is your query is doing this:

WHERE
 (ACCDAT_0 >= '2020-01-01 00:00:00.000' and
  STA_0='3' and
  NUM_0 LIKE '%FTC%') OR NUM_0 LIKE '%NCC%' OR NUM_0 LIKE '%DCF%'
  

Meaning if NUM_0 is like NCC or DCF, then the first two criteria are ignored. That may not be what you meant, but that's what you said.

You might have meant this:

WHERE
  ACCDAT_0 >= '2020-01-01 00:00:00.000' and
  STA_0='3' and
 (NUM_0 LIKE '%FTC%' OR NUM_0 LIKE '%NCC%' OR NUM_0 LIKE '%DCF%')

And the larger lesson is... if you mix AND and OR, be sure to use parentheses so it does exactly what you mean.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hambone