SQL: AND / OR Statement Sequence

What I'm trying to solve for: Where is the operator, where the query checks if Condition 1 A OR B WHILE Condition 2 is NOT C, D on the same line.

WHERE Condition1 LIKE 'A' OR Condition1 LIKE 'B' AND "Condition2" <> 'C' AND "Condition2" <> 'D'

It's close? Many thanks!

+4
source share
2 answers

You are on the right track, but you are missing something that ANDhas a higher priority than OR. The most elegant way to express your desired condition:

SELECT *
FROM   some_table
WHERE  c1 IN ('A', 'B') AND c2 NOT IN ('C', 'D');   
+2
source

You must group your subexpressions in parentheses, otherwise you risk ambiguity around what is grouped:

WHERE
    (Condition1 = 'A' OR Condition1 = 'B')
    AND
    (Condition2 <> 'C' AND Condition2 <> 'D')

, AND, OR .

, :

WHERE
    Condition1 = 'A'
    OR
    (Condition1 = 'B' AND Condition2 <> 'C' AND Condition2 <> 'D')
+2

All Articles