thecodex.expert · The Codex Family of Knowledge
SQL

Filtering with WHERE

WHERE is evaluated per row before anything is selected — it decides which rows even make it into the result, not which columns are shown.

SQL:2016 / ANSI Runs before SELECT Last verified:
Canonical Definition

WHERE evaluates a boolean condition for every row in the source table, keeping only rows where the condition is true. Conditions combine comparison operators (=, <>, <, >), logical operators (AND, OR, NOT), range checks (BETWEEN), set membership (IN), and pattern matching (LIKE) into arbitrarily complex expressions.

Comparison and logical operators

Standard comparisons combine with AND/OR/NOT; parentheses control evaluation order exactly like in a programming language's boolean expressions.

SQLwhere_basics.sql
SELECT * FROM products
WHERE price > 50 AND category = 'electronics';

SELECT * FROM products
WHERE (category = 'electronics' OR category = 'books')
  AND in_stock = true;

BETWEEN and IN: ranges and sets

BETWEEN is inclusive of both endpoints; IN checks membership in a list, a much cleaner alternative to a chain of OR conditions on the same column.

SQLbetween_in.sql
SELECT * FROM orders
WHERE order_date BETWEEN '2026-01-01' AND '2026-01-31';   -- inclusive both ends

SELECT * FROM products
WHERE category IN ('electronics', 'books', 'toys');        -- instead of 3 ORs

LIKE: pattern matching

% matches any sequence of characters (including none); _ matches exactly one character. Matching is case-sensitive by default in most engines, with ILIKE (PostgreSQL) or LOWER() as common case-insensitive workarounds.

SQLlike.sql
SELECT * FROM users WHERE email LIKE '%@gmail.com';   -- ends with
SELECT * FROM users WHERE name LIKE 'A%';               -- starts with 'A'
SELECT * FROM users WHERE name LIKE '_ohn';             -- exactly 4 chars, ends "ohn"

Sources

1
PostgreSQL Global Development Group. PostgreSQL Documentation, "Value Expressions" and "Pattern Matching", postgresql.org/docs.