Skip to main content
Back to SQL Coding

SQL Coding · Reading the Query

Filtering with WHERE

The one idea: WHERE decides which rows survive before anything is counted, so a filtering mistake makes every later number wrong even when the math is perfect. The two things that quietly break filters: mixing "and" with "or" without parentheses, and assuming a "not equal" test includes rows with missing values.
⚠️ The trap: state = 'CA' OR state = 'NY' AND total_spent > 500 reads left to right, so it's CA-or-NY customers who spent over $500 — just like the English sentence. That feels right and it's wrong. SQL always does AND before OR, so that clause really means "every CA customer, plus only the big-spender NY ones" — wrap the OR in parentheses to get what you meant.

WHERE decides which rows survive before anything gets counted, summed, or displayed. Get WHERE wrong — or misread it — and every number downstream is confidently calculated from the wrong data.

The core idea

SELECT *
FROM orders
WHERE status = 'completed'
  AND order_date >= '2026-01-01'

This keeps only rows where both conditions are true. Change AND to OR and the meaning flips completely — now a row survives if either condition is true, which usually returns far more rows than intended. When you're reading a query someone else wrote (or an AI generated), the single highest-leverage thing to check is whether AND and OR are doing what the author's explanation claims they're doing.

AND vs OR — where it actually bites

Say a stakeholder asks for "customers in California or New York who spent over $500." A correct query:

WHERE (state = 'CA' OR state = 'NY') AND total_spent > 500

Keep reading: Filtering with WHERE

Sign up free to read the full lesson, ask the AI tutor, and take practice questions.

  • Full lesson content
  • AI tutor for this section
  • Practice questions