Hone

Lessons · SQL · AND before OR

AND binds tighter than OR

a AND b OR c means (a AND b) OR c. Use parentheses to say what you mean.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

The unbracketed OR that silently disables another condition is one of the most common production SQL bugs.

How to think about it

Does this WHERE mix AND and OR? Whenever a WHERE has both AND and OR, add parentheses around the OR group even if you think you do not need them.

Worked example

WHERE status = 'paid' AND (city = 'Leeds' OR amount > 70)
Paid, and one of the two.
WHERE status = 'paid' AND city = 'Leeds' OR amount > 70
Paid-and-Leeds, OR any amount over 70 including refunds. Different.

Your turn

Group the alternatives.

WHERE active = 1 AND role = 'admin' OR role = 'owner';

The trap

Trusting the mental precedence of English. Brackets cost nothing.

Practise AND before OR on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.