3.3 CASE WHEN, Conditional Aggregation & Pivoting Data
Write if-else logic inside SQL with CASE WHEN, compute multiple filtered KPIs in a single table scan using Conditional Aggregation (SUM(CASE WHEN ...)), and pivot rows into columns.
1. If-Else Logic Inside SQL (CASE WHEN)
CASE WHEN is SQL's built-in if / elif / else expression. You can place it almost anywhere an expression is valid: inside SELECT to bucket metrics, inside ORDER BY for custom priority sorting, inside GROUP BY to group by dynamic tiers, or inside aggregate functions like SUM() and COUNT().
Crucially, CASE WHEN short-circuits from top to bottom and returns the value of the first branch that evaluates to TRUE. Once a row matches a WHEN condition, SQL skips all remaining branches — which means you should always order range thresholds from most restrictive to least restrictive (for example, >= 90 before >= 75).
SELECT
name,
score,
CASE
WHEN score >= 90 THEN 'A (Distinction)'
WHEN score >= 75 THEN 'B (First Class)'
WHEN score >= 50 THEN 'C (Pass)'
ELSE 'F (Needs Review)'
END AS grade
FROM students
ORDER BY score DESC;
3 Common CASE WHEN Pitfalls to Avoid
- Missing
ELSEsilently returnsNULL: If noWHENbranch matches and you omitELSE, SQL returnsNULL— which can later breakCONCAT()or skew averages. Always add an explicitELSEunlessNULLis intentional. - Never write
CASE col WHEN NULL: In SQL three-valued logic,col = NULLis alwaysUNKNOWN, neverTRUE! Always use the SearchedCASEsyntax (WHEN col IS NULL THEN ...) whenever checking for missing values. - Keep
THENreturn types compatible: Every branch in aCASEexpression must resolve to a compatible data type (don't return'Free'in one branch and integer100in another — cast both to text or keep both numeric).
Simple CASE vs Searched CASE
| Style | Syntax | Best For |
|---|---|---|
Simple CASE | CASE status WHEN 'paid' THEN 1 ELSE 0 END | Exact equality checks on one non-null column |
Searched CASE (Recommended) | CASE WHEN score >= 90 AND active THEN 'Top' ELSE 'Std' END | Ranges (>=, <), IS NULL, and compound AND/OR logic |
2. The Analytics Superpower: Conditional Aggregation (Pivoting Rows → Columns)
Suppose a product manager asks for one executive dashboard table showing each city's total_orders, paid_orders, cancelled_orders, paid_revenue, and conversion_pct.
Beginners run three separate queries with different WHERE status = ... filters and stitch them together in Python or Excel. On a 20-million-row orders table, that forces the database to scan the table three separate times. Senior engineers compute every metric in ONE single table scan using Conditional Aggregation — wrapping CASE WHEN inside SUM():
SELECT
city,
COUNT(*) AS total_orders,
SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_orders,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled_orders,
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid_revenue,
ROUND(
100.0 * SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) / COUNT(*),
1
) AS conversion_pct
FROM orders
GROUP BY city
ORDER BY paid_revenue DESC;
Classic SQL Interview Trap (
SUMvsCOUNT): Never writeCOUNT(CASE WHEN status = 'paid' THEN 1 ELSE 0 END)! BecauseCOUNT()counts every non-NULL value (including0), that expression returns the total row count instead of paid rows. Either useSUM(... THEN 1 ELSE 0 END)or drop theELSE 0so unmatched rows evaluate toNULL:COUNT(CASE WHEN status = 'paid' THEN 1 END).
PostgreSQL vs MySQL Shorthands
Standard SUM(CASE WHEN ...) works identically across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery, so it is your safest choice for interviews and portable SQL. However, both major engines also offer concise dialects:
- PostgreSQL (ANSI SQL Standard): Supports the ultra-readable
FILTER (WHERE ...)clause on any aggregate function:
SELECT
city,
COUNT(*) AS total_orders,
COUNT(*) FILTER (WHERE status = 'paid') AS paid_orders,
COALESCE(SUM(amount) FILTER (WHERE status = 'paid'), 0) AS paid_revenue
FROM orders
GROUP BY city;
- MySQL: Evaluates boolean expressions as
1(true) or0(false), so you will often seeSUM(status = 'paid')in MySQL codebases. Avoid relying on that in PostgreSQL, which strictly separatesBOOLEANfromINTEGER.
3. Bonus Production Pattern: Custom ORDER BY Sorting with CASE WHEN
Alphabetical sorting fails whenever a column has business-defined priority levels like 'urgent', 'high', 'medium', and 'low' (alphabetically 'high' would wrongly come before 'urgent'). Put CASE WHEN directly inside ORDER BY to define any custom sort rank:
SELECT ticket_id, title, priority
FROM support_tickets
WHERE is_open = TRUE
ORDER BY
CASE priority
WHEN 'urgent' THEN 1
WHEN 'high' THEN 2
WHEN 'medium' THEN 3
ELSE 4
END,
created_at ASC;
4. Watch Conditional Aggregation Pivot a Table Live
| city | status | amt |
|---|---|---|
| Bengaluru | paid | 1200 |
| Bengaluru | cancelled | 800 |
| Bengaluru | paid | 500 |
| Pune | paid | 900 |
5. Quick Check Your Understanding
Module 3.3 Quick Quiz
Keep Exploring: Related Lessons & Tools
All Courses →Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.
Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.