Question presented to candidate: "SQL has no if statement inside a query, yet reports constantly need 'if this then that'. Explain the CASE expression: its two forms, how it decides which branch wins, what happens when nothing matches, and show me two or three places you would use it."
What a strong answer should cover:
- CASE is an expression that returns one value per row, usable anywhere a value is: SELECT, WHERE, ORDER BY, GROUP BY, inside aggregates, in UPDATE ... SET
- The searched form (
CASE WHEN condition THEN ...) and the simple form (CASE expr WHEN value THEN ...); WHEN branches are tested top to bottom and the first true one wins - No ELSE means NULL when nothing matches; the simple form compares with
=, soWHEN NULLnever matches and you needWHEN x IS NULL - Common uses: bucketing values, custom sort orders, conditional aggregation (pivot-style counts), guarding division by zero
- Engine details: all branches must have compatible types in PostgreSQL (SQLite does not care); PostgreSQL may evaluate a constant in an unused branch at plan time; SQLite has
iif(), PostgreSQL does not
Code / implementation expected: Yes β a searched CASE that buckets a value, ideally also a CASE inside SUM or COUNT.
Schema used by the examples: