WHERE
WHERE
Definition
WHERE filters rows, keeping only those where a condition evaluates to TRUE — the direct SQL implementation of relational algebra's Selection (7.1).
Running example — a products(id, name, category, price, stock) table, where stock can be NULL (not yet counted):
| id | name | category | price | stock |
|---|---|---|---|---|
| 1 | ProLaptop | Electronics | 85000 | 12 |
| 2 | Notebook | Stationery | 40 | NULL |
| 3 | Python Basics | Books | 350 | 5 |
| 4 | ProPhone | Electronics | 45000 | 0 |
sqlSELECT name, price FROM products WHERE category = 'Electronics' AND price > 50000;
WHERE is evaluated per-row, BEFORE any grouping (GROUP BY) happens — this is exactly why WHERE cannot reference an aggregate like SUM(price) (that's what HAVING is for, Chapter 15). A WHERE condition can combine comparisons (12.4), logical operators (12.5), ranges (BETWEEN, 12.6), set membership (IN, 12.7), pattern matching (LIKE, 12.8), and NULL tests (IS NULL, 12.10) — all the topics in the rest of this chapter are building blocks for WHERE conditions.
Edge Cases and Pitfalls
- Rows where the
WHEREcondition evaluates toUNKNOWN(usually from aNULLcomparison) are excluded, exactly likeFALSErows — this is the three-valued-logic behavior from Chapter 8's NULL Semantics. - Omitting
WHEREentirely from aSELECTreturns every row — harmless forSELECT, but the same omission onUPDATE/DELETEis a serious, common mistake (Chapter 11). WHEREconditions are evaluated left-to-right respecting operator precedence (12.15) — parenthesizing compound conditions explicitly, even when not strictly required, makes intent clearer and avoids precedence mistakes.
Key Takeaways
WHEREfilters individual rows before any grouping; it's the SQL form of relational Selection.- It cannot reference aggregate functions — that's HAVING's job (Chapter 15).
- Every filtering technique in this chapter (comparisons, BETWEEN, IN, LIKE, IS NULL) is a building block for WHERE conditions.