The WHERE clause filters table rows by evaluating a Boolean condition and returning only rows that match.
Use WHERE and FILTER clauses to return only the rows that meet your conditions, reduce scan time, and speed up queries.
The WHERE clause evaluates a Boolean expression for every row and returns only rows where the expression is true. This filters data at the row level before aggregation or ordering.
Start a SELECT, list the columns, add FROM table_name
, then append WHERE followed by one or more conditions. Combine conditions with AND, OR, and parentheses for precedence.
Retrieve users from the USA:SELECT * FROM users WHERE country = 'USA';
Combine checks:SELECT * FROM users WHERE active AND (country = 'USA' OR country = 'CAN');
Find names that start with S, case-insensitive:SELECT * FROM users WHERE name ILIKE 's%';
Return orders placed in 2024:SELECT * FROM orders WHERE order_date BETWEEN '2024-01-01' AND '2024-12-31';
Only rows where phone is missing:SELECT * FROM customers WHERE phone IS NULL;
Use FILTER (WHERE ...)
inside aggregate functions to include only matching rows without a subquery.
SELECT count(*) FILTER (WHERE status = 'open') AS open_count FROM tickets;
1. Create indexes on columns often used in WHERE.
2. Compare to constants or parameters, not functions, to keep indexes usable.
3. Use EXPLAIN to verify index usage.
SELECT id, name, created_at FROM customers WHERE country = 'USA' AND active = true ORDER BY created_at DESC LIMIT 50;
Use IS NULL instead of = NULL, and enclose OR conditions in parentheses when mixed with AND.
Yes. PostgreSQL executes WHERE to filter rows first, then groups the surviving rows. Use HAVING to filter after aggregation.
Yes. Use expressions in WHERE, but wrap them in parentheses and beware of functions that prevent index usage.
Use the ->> operator to extract JSON text before comparison: WHERE data->>'status' = 'open'
.