Skip to content
C

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):

idnamecategorypricestock
1ProLaptopElectronics8500012
2NotebookStationery40NULL
3Python BasicsBooks3505
4ProPhoneElectronics450000
sql
SELECT 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 WHERE condition evaluates to UNKNOWN (usually from a NULL comparison) are excluded, exactly like FALSE rows — this is the three-valued-logic behavior from Chapter 8's NULL Semantics.
  • Omitting WHERE entirely from a SELECT returns every row — harmless for SELECT, but the same omission on UPDATE/DELETE is a serious, common mistake (Chapter 11).
  • WHERE conditions 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

  • WHERE filters 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.

Mock Test

  • WHERE - Quick Test

    8 questions on WHERE.

    8 questions · 8 min · Medium
    Start Mock Test

Coding Problem