pbPassingBI
/
Foundations & querying beginner 5 min

Combining conditions with AND, OR and NOT

Boolean logic and the precedence rule that causes wrong results.

What you'll be able to do
  • Combine conditions correctly
  • Apply operator precedence
  • Use parentheses to make intent explicit

The operators

WHERE city = 'Houston' AND total > 100
WHERE city = 'Houston' OR  city = 'Dallas'
WHERE NOT status = 'cancelled'

AND requires both sides true. OR requires either. NOT inverts.

Precedence — the trap

AND binds tighter than OR. This causes more wrong results than any other beginner mistake.

-- probably not what was meant
WHERE city = 'Houston' OR city = 'Dallas' AND total > 100

Because AND binds first, this reads as all Houston orders, plus Dallas orders over 100. The intended meaning almost always needs parentheses:

WHERE (city = 'Houston' OR city = 'Dallas')
  AND total > 100

The query runs either way and returns plausible numbers, which is exactly why the bug survives review.

Parenthesise anyway

Even where precedence gives the result you want, parentheses cost nothing and remove all doubt for whoever reads the query next — including you in six months.

Key points
  • AND is evaluated before OR
  • Mixing AND and OR without parentheses is a common source of silent bugs
  • Parenthesise mixed conditions even when precedence would be correct
Check yourself