SQL Practice Logo

SQLPractice Online

WHERE Clause & Filtering: Concept

Module: SQL Fundamentals

WHERE is the row-selection gate of every SQL query. It evaluates each row against one or more conditions and passes only rows where the expression evaluates to TRUE — not FALSE, not UNKNOWN. Understanding WHERE at a deep level means understanding NULL three-valued logic, operator precedence, sargability, and index interaction: the four pillars that separate fast queries from slow ones.

WHERE IN THE LOGICAL PROCESSING ORDER

SQL processes a query in a fixed logical order that is different from the written order. WHERE sits at step 3:

1. FROM — load base tables and apply JOINs (produce working set)

2. ON — apply join predicates

3. WHERE — filter rows (eliminates rows from further processing)

4. GROUP BY — group surviving rows

5. HAVING — filter groups

6. SELECT — project columns and evaluate expressions

7. DISTINCT — remove duplicates

8. ORDER BY — sort

9. LIMIT/FETCH — page results

Because WHERE runs before SELECT, you cannot reference SELECT aliases in WHERE. Because it runs before GROUP BY, you cannot filter aggregates in WHERE (that is HAVING's job). Every row eliminated by WHERE means fewer rows for every downstream step — this is why WHERE is the highest-leverage performance tool in SQL.

---

THREE-VALUED LOGIC: TRUE / FALSE / UNKNOWN

SQL uses three-valued logic, not binary. A condition can evaluate to:

- TRUE — row is included

- FALSE — row is excluded

- UNKNOWN — row is excluded (same behavior as FALSE)

UNKNOWN arises whenever NULL participates in a comparison. This is the source of the most common SQL bugs:

NULL = NULL evaluates to UNKNOWN (not TRUE!)

NULL != NULL evaluates to UNKNOWN

NULL = 1 evaluates to UNKNOWN

NULL > 0 evaluates to UNKNOWN

NOT UNKNOWN evaluates to UNKNOWN

The practical consequence: WHERE col = NULL returns zero rows because every evaluation produces UNKNOWN. The only correct NULL tests are IS NULL and IS NOT NULL, which bypass three-valued logic entirely.

NULL in AND/OR:

TRUE AND UNKNOWN = UNKNOWN

FALSE AND UNKNOWN = FALSE (FALSE wins)

TRUE OR UNKNOWN = TRUE (TRUE wins)

FALSE OR UNKNOWN = UNKNOWN

---

AND / OR OPERATOR PRECEDENCE

AND binds tighter than OR — the same way multiplication binds tighter than addition. This is the most frequent WHERE logic bug:

Wrong: WHERE country = 'US' OR country = 'CA' AND status = 'active'

Parsed: WHERE country = 'US' OR (country = 'CA' AND status = 'active')

The query returns ALL US rows regardless of status. The fix is explicit parentheses:

Correct: WHERE (country = 'US' OR country = 'CA') AND status = 'active'

Rule: whenever you mix AND and OR, always use parentheses. Do not rely on operator precedence for correctness or readability.

---