Skip to content
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 valid either way, so nothing errors — the wrong rows just come back, silently. The defence is knowing the precedence rule and always parenthesising your OR groups.

The mental model: AND is like multiplication, OR like addition. Just as 2 + 3 * 4 is 2 + 12 = 14 (not 5 * 4), A OR B AND C is A OR (B AND C) — not (A OR B) AND C.

AND  binds first   (like × in arithmetic)
OR   binds second  (like + in arithmetic)

A worked example — the classic bug

Intent: “active users in NY or CA.” Written without parentheses, it does something else entirely:

-- Bug: AND binds first, so this means (active AND NY) OR (anyone in CA)
SELECT id, name, status, state
FROM users
WHERE status = 'active' AND state = 'NY' OR state = 'CA';
idnamestatusstate
1AaravactiveNY
3ChenactiveCA
4DarainactiveCA

There’s the bug, plain as day: Dara is inactive, yet she’s in the result — because OR state = 'CA' admits anyone from California, status be damned. The query ran, returned rows, and quietly included someone it shouldn’t have.

Parenthesise the OR group and intent is restored:

SELECT id, name, status, state
FROM users
WHERE status = 'active' AND (state = 'NY' OR state = 'CA');
idnamestatusstate
1AaravactiveNY
3ChenactiveCA

Now only active users in either state come through — Dara is correctly excluded. One pair of parentheses is the whole fix.

Learn it properly WHERE & filtering

Keep practising

All SQL questions

Explore further