CASE Expressions and Pivot Queries
Use CASE WHEN inside aggregates to pivot tall tables into wide cross-tab reports.
CASE: Inline If/Else for SQL
CASE is the SQL ternary. Two forms:
-- Searched CASE
CASE WHEN x > 0 THEN 'positive'
WHEN x < 0 THEN 'negative'
ELSE 'zero' END
-- Simple CASE
CASE status
WHEN 'A' THEN 'active'
WHEN 'P' THEN 'pending'
ELSE 'unknown'
ENDCASE in SELECT
Compute a derived column:
SELECT id, total,
CASE
WHEN total >= 1000 THEN 'whale'
WHEN total >= 100 THEN 'regular'
ELSE 'small'
END AS bucket
FROM orders;All lessons in this course
- UNION, INTERSECT, EXCEPT
- UNION ALL vs UNION (Deduplication Cost)
- CASE Expressions and Pivot Queries
- Crosstab Patterns (PostgreSQL crosstab())