Lesson Beginner

AND / OR / NOT

Most real filters are multi-part: paid orders from this quarter, customers in these three countries but not trial accounts, etc.
AND, OR, and NOT are how you combine conditions. Most filtering bugs come from boolean logic mistakes, not from syntax, so it is worth slowing down here.

The Three Connectors #

  • AND: every condition must be true. Adding AND makes the result narrower.
  • OR: at least one condition must be true. Adding OR makes the result wider.
  • NOT flips a condition. NOT condition is true when condition is false.
sql
-- AND: paid orders over 100
SELECT id, status, total
FROM orders
WHERE status = 'paid' AND total > 100;

-- OR: any order that is paid or pending
SELECT id, status, total
FROM orders
WHERE status = 'paid' OR status = 'pending';

-- NOT: anything that is not cancelled
SELECT id, status, total
FROM orders
WHERE NOT status = 'cancelled';

Precedence: AND Binds Tighter Than OR #

When you mix AND and OR, AND is evaluated first.
That rule is the single biggest source of silent filtering bugs.

sql
-- Looks like: "paid or pending, with total > 100"
-- Actually means: "paid, OR (pending AND total > 100)"
WHERE status = 'paid'
   OR status = 'pending' AND total > 100;

-- Write what you mean with explicit parentheses:
WHERE (status = 'paid' OR status = 'pending')
  AND total > 100;
Warning

When you mix AND and OR, always use parentheses.
It costs two characters, removes all ambiguity, and protects your query from silently returning the wrong rows when someone edits it six months from now.

Try It #

Run the query below. Then remove the parentheses around (status = 'paid' OR status = 'pending') and compare the row counts.

Loading SQL editor...

Practice #

Return id, status, and total for orders that are either paid with a total strictly greater than 100, or pending (any total). No ordering requirement.

Loading SQL editor...

Mistakes to Watch For #

  • Relying on AND/OR precedence without parentheses.
  • NOT with a nullable column: NOT col = 'x' is UNKNOWN when col is NULL, so those rows silently drop. Use col IS DISTINCT FROM 'x' or handle NULLs explicitly.
  • Writing OR chains when IN would be clearer (covered in the next lesson).
  • Thinking != and <> differ. They are the same operator in every major dialect.

Knowledge check #

4 questions

0 / 4 answered
  1. Without parentheses, WHERE region = 'EU' OR region = 'US' AND status = 'paid' is equivalent to:

  2. WHERE NOT (status = 'cancelled' OR status = 'refunded') is equivalent to (by De Morgan's laws):

  3. WHERE col NOT IN (1, 2, NULL) returns:

  4. Which two operators always mean the same thing in standard SQL?

Next Step #

Continue to IN / BETWEEN to express multi-value and range filters without stacking ORs.