datarekha
SQL Easy Asked at Amazon

How does operator precedence work with AND and OR in a WHERE clause?

The short answer

AND binds more tightly than OR, just like multiplication binds more tightly than addition. Without parentheses, the expression A OR B AND C is evaluated as A OR (B AND C), not (A OR B) AND C. Always use parentheses when mixing AND and OR to make intent explicit.

How to think about it

This is a sneaky correctness question. The SQL is syntactically valid either way, so no error is thrown — the wrong rows just come back silently. Knowing the precedence rule and always parenthesizing OR groups is the safeguard.

The mental model

Think of AND like multiplication and OR like addition. Just as 2 + 3 * 4 evaluates as 2 + 12 = 14 (not 5 * 4 = 20), A OR B AND C evaluates as A OR (B AND C) — not (A OR B) AND C.

The classic bug — run it and see

Without the parentheses, status = 'active' AND state = 'NY' binds first, then OR state = 'CA' lets in anyone from California regardless of their status. That is almost certainly wrong.

The correct pattern

Always wrap OR groups in parentheses when mixing with AND:

-- Active users in either NY or CA
SELECT * FROM users
WHERE status = 'active'
  AND (state = 'NY' OR state = 'CA');

For three or more conditions this becomes even more important. Be explicit — don’t make the reader (or future you) remember precedence rules.

Learn it properly WHERE & filtering

Keep practising

All SQL questions

Explore further

Skip to content