Interview Q&A · SQL · 14 questions in this topic
Filtering: WHERE in Depth — SQL Interview Q&A
Precise row selection — comparisons, LIKE, IN, BETWEEN, NULL checks and three-valued logic. Part of SELECT & Filtering · 192 questions in the SQL bank.
How does WHERE filter rows? What can it reference?
Answer
WHERE keeps rows where its predicate is TRUE (not FALSE, not UNKNOWN) and runs before SELECT — so it sees base columns and expressions over them, but not SELECT aliases or aggregates. One table predicate per concern, combined with AND/OR/NOT, beats clever mega-conditions.
Sargability matters: WHERE salary * 12 > x defeats indexes where WHERE salary > x / 12 does not.
Example
SELECT name FROM employees WHERE department = 'Engineering' AND salary > 70000;
💡 TRUE-only plus runs-before-SELECT explains nearly every WHERE error.
How do AND, OR, NOT combine, and why do parentheses matter?
Answer
Precedence: NOT, then AND, then OR. So a AND b OR c parses as (a AND b) OR c — mixing without parens silently widens/narrows the filter. Parenthesize mixed logic explicitly; -style review rules flag bare AND/OR mixes.
De Morgan helps invert: NOT (a AND b) is (NOT a) OR (NOT b).
Example
-- intended: Engineering seniors OR any manager SELECT * FROM employees WHERE (department = 'Engineering' AND salary > 90000) OR title = 'Manager';
How does LIKE pattern matching work (% and _)?
Answer
% matches any run (including empty), _ matches exactly one character. LIKE is case-sensitive in PostgreSQL (ILIKE for insensitive) and case-insensitive in MySQL default collations — a classic portability trap. Leading % (LIKE '%x') defeats B-tree indexes; full-text/trigram indexes serve substring search.
Escape literals with ESCAPE when patterns contain % or _ themselves.
Example
SELECT name FROM employees WHERE name LIKE 'A%'; -- starts with A SELECT name FROM employees WHERE name LIKE '%son'; -- ends with son (slow)
How do IN and NOT IN work, and what is the NULL trap?
Answer
IN matches membership (col IN (1, 2, 3) or a subquery); NOT IN excludes — but if the list contains NULL, NOT IN returns UNKNOWN for every row, i.e. no rows at all. This NULL poisoning is the most famous IN trap.
Safe forms: NOT EXISTS (immune), or filter NULLs from the subquery. IN with huge lists also bloats plans — temp tables or joins scale better.
Example
-- NULL-poisoned: returns NOTHING if subquery has any NULL -- SELECT * FROM e WHERE id NOT IN (SELECT id FROM x); -- safe: SELECT * FROM e WHERE NOT EXISTS (SELECT 1 FROM x WHERE x.id = e.id);
How do you test for NULL (IS NULL) and why does `= NULL` fail?
Answer
NULL means unknown, so = NULL evaluates to UNKNOWN (not TRUE) and matches nothing — use IS NULL / IS NOT NULL. COUNT(col), aggregates and DISTINCT all skip NULLs; NOT IN is poisoned by them.
Three-valued logic (TRUE/FALSE/UNKNOWN) with WHERE keeping only TRUE is the complete theory.
Example
SELECT name FROM employees WHERE bonus IS NULL; -- correct -- WHERE bonus = NULL -- matches NOTHING, always
💡 UNKNOWN is not TRUE is the sentence that unlocks all NULL behavior.
How does BETWEEN work (inclusive)? What are its edges?
Answer
BETWEEN is inclusive on both ends (x BETWEEN 1 AND 5 means 1..5) — a symmetric shorthand for >= AND <=. Edges: reversed bounds match nothing, NULL bounds poison to UNKNOWN, and date ranges need care (BETWEEN '2024-01-01' AND '2024-01-31' misses Jan-31 afternoon timestamps).
Half-open ranges (>= start AND < next) are safer for continuous domains like timestamps.
Example
-- safer date range: half-open SELECT * FROM orders WHERE created_at >= '2024-01-01' AND created_at < '2024-02-01';
How do `!=`, `<>` and `NOT` differ? How do they treat NULLs?
Answer
!= and <> are the same not-equal operator (spelling varies by habit/dialect). Both yield UNKNOWN on NULL — so != filters NULLs out silently. NOT flips TRUE/FALSE but leaves UNKNOWN as UNKNOWN.
To include NULLs, add OR col IS NULL explicitly — nothing includes them by default.
Example
SELECT * FROM employees WHERE department <> 'Sales'; -- NULL-department rows are EXCLUDED (UNKNOWN, not TRUE)
What is three-valued logic (TRUE / FALSE / UNKNOWN)?
Answer
SQL predicates evaluate to TRUE, FALSE or UNKNOWN (any operation on NULL). WHERE keeps only TRUE rows; CHECK constraints accept TRUE and UNKNOWN (rejecting only FALSE); UNIQUE treats NULLs as distinct (mostly). NOT UNKNOWN stays UNKNOWN.
Every NULL surprise — vanishing rows, poisoned NOT IN, permissive CHECKs — is this logic playing out.
Key points
- 1WHERE — keeps TRUE only.
- 2CHECK — rejects FALSE only (NULL passes!).
- 3NOT UNKNOWN — still UNKNOWN.
Example
CHECK (salary > 0) -- NULL salary PASSES (UNKNOWN, not FALSE)!
💡 WHERE-strict vs CHECK-lenient is the contrast interviewers probe.
How do you filter on dates and times?
Answer
Compare with typed literals (DATE '2024-01-01'), range half-open for timestamp days, extract parts with EXTRACT/date_trunc, and interval arithmetic for offsets. Never compare dates as strings (format-dependent) or wrap indexed columns in functions (unsargable).
Time-zone storage (TIMESTAMPTZ) plus AT TIME ZONE display keeps global data correct.
Example
SELECT * FROM orders WHERE created_at >= DATE '2024-01-01' AND created_at < DATE '2024-02-01';
What makes a WHERE clause fast (sargability)?
Answer
Sargable predicates let the engine seek an index: bare column compared to a value (col = ?, col > ?). Non-sargable forms — functions on columns, leading-% LIKE, arithmetic wrapping, implicit type conversions — force full scans.
Write filters index-first: bare columns, matching types, selective conditions first for readability (planner reorders anyway).
Key points
- 1Sargable — bare column vs value, index-seekable.
- 2Scan-forcing — functions, leading %, conversions.
- 3Fix — computed/expression indexes or rewritten predicates.
Example
-- slow: WHERE YEAR(hired) = 2024; -- fast: WHERE hired >= DATE '2024-01-01' AND hired < DATE '2025-01-01';
💡 Bare-column-vs-value is the sargability test you can apply to any predicate.
How do EXISTS and NOT EXISTS work?
Answer
EXISTS tests whether a correlated subquery returns any row — TRUE/FALSE, never UNKNOWN, immune to NULL poisoning. It short-circuits on the first match and ignores the SELECT list (SELECT 1 is idiom). NOT EXISTS is the safe anti-join.
Prefer EXISTS over IN for correlated checks and over COUNT(*) > 0 for existence tests.
Example
SELECT name FROM employees e WHERE EXISTS (SELECT 1 FROM departments d WHERE d.dept_id = e.department);
💡 NULL-immune anti-join is the NOT EXISTS headline.
How do you find rows missing a match (anti-join patterns)?
Answer
Three forms: NOT EXISTS (safe, readable, NULL-immune), LEFT JOIN ... WHERE right.key IS NULL (visible, sometimes planner-friendly), NOT IN (concise but NULL-poisoned — avoid with nullable sets). All express employees-without-departments style questions.
Default to NOT EXISTS; reach for LEFT JOIN/IS NULL when the plan proves better.
Example
-- employees with no matching department: SELECT e.* FROM employees e WHERE NOT EXISTS (SELECT 1 FROM departments d WHERE d.dept_id = e.department);
How do you deduplicate rows (keep one per group)?
Answer
GROUP BY with MIN/MAX picks per group; PostgreSQL DISTINCT ON returns the first row per group under an ORDER BY; window ROW_NUMBER() partitioned by the key with outer filter rn = 1 is portable and flexible (choose latest per user by ordering inside).
DISTINCT alone cannot pick which duplicate survives — these three can.
Example
SELECT * FROM (SELECT *, ROW_NUMBER() OVER ( PARTITION BY email ORDER BY created_at DESC) AS rn FROM users) t WHERE rn = 1; -- latest row per email
💡 ROW_NUMBER-partition-filter is the portable dedup pattern worth memorizing.
How do you write filters that stay correct under NULLs?
Answer
Enumerate nullability per predicate: add OR col IS NULL where inclusion is intended, use COALESCE to canonicalize before comparison, prefer NOT EXISTS over NOT IN, and IS DISTINCT FROM (standard) for null-aware inequality.
The discipline: for every <> / NOT IN / comparison, ask what NULL does — then handle it explicitly.
Example
SELECT * FROM employees WHERE department IS DISTINCT FROM 'Sales'; -- NULL-safe <>, standard SQL
💡 IS DISTINCT FROM is the null-safe comparison to name-drop.
Recommended resourcesAffiliate links · may earn us a commission