Pivoting Data Using Conditional Aggregation (SUM(CASE WHEN ...))
Pivot categories into columns with SUM/COUNT(CASE WHEN ...) patterns.
In plain words
For each new column, add up only the rows that belong in that column.
Think of it like…
Turning a long list of receipts into a spreadsheet with one row per month and one column per shop: for each cell you add up only the receipts that match both that month and that shop.
Where you’ve seen it
A monthly status report: SELECT date_trunc('month', created_at) AS month, COUNT(*) FILTER (WHERE status = 'paid') AS paid, COUNT(*) FILTER (WHERE status = 'refunded') AS refunded, COUNT(*) FILTER (WHERE status = 'cancelled') AS cancelled FROM orders GROUP BY 1 ORDER BY 1;
Words you’ll hear
- Long format
- One row per observation (month, status, value).
- Wide format
- One row per entity, one column per category.
- Conditional aggregation
- An aggregate over a CASE or FILTER that counts only matching rows.
- Dynamic pivot
- Columns decided by the data at run time; needs dynamic SQL or a BI tool.
Visual diagram
Theory & example queries
Pivoting with CASE or FILTER
GROUP BY the row dimension (month), then write one aggregate per column. SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) sums paid amounts; COUNT(CASE WHEN status = 'paid' THEN 1 END) counts paid rows (no ELSE, so other rows are NULL and not counted). PostgreSQL, SQLite and DuckDB support the clearer COUNT(*) FILTER (WHERE status = 'paid').
Some databases have a dedicated operator: SQL Server and Oracle have PIVOT, and PostgreSQL has crosstab() in the tablefunc extension. Conditional aggregation works everywhere and is easier to read and maintain, so it's the usual interview answer.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
SELECT date_trunc('month', o.created_at) AS MONTH, SUM( CASE WHEN p.category = 'books' THEN o.amount ELSE 0 END ) AS books, SUM( CASE WHEN p.category = 'toys' THEN o.amount ELSE 0 END ) AS toysFROM orders o JOIN products p ON p.id = o.product_idGROUP BY 1;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output3 sample rows
| month | books | toys |
|---|---|---|
| 2026-09-01 | 12800 | 9400 |
| 2026-10-01 | 15150 | 11200 |
| 2026-11-01 | 6800 | 5250 |
Note: Illustrative monthly category totals in currency units.
Key takeaway: GROUP BY the rows; one conditional aggregate per column.
Dynamic columns and unpivoting
SQL needs to know the output columns when the query is written, so a pivot can't automatically add a column for a category that appears next month. Options: generate the query in code from the list of categories (dynamic SQL), or return the long format and let the BI tool or spreadsheet pivot it.
Unpivoting goes the other way, turning columns into rows, which is useful for normalising spreadsheet-style imports. Use UNION ALL of one SELECT per column, or in PostgreSQL CROSS JOIN LATERAL (VALUES ('q1', q1), ('q2', q2)) v(quarter, amount).
SELECT s.region, v.quarter, v.amountFROM sales_wide s CROSS JOIN LATERAL ( VALUES ('Q1', s.q1), ('Q2', s.q2), ('Q3', s.q3), ('Q4', s.q4) ) AS v (quarter, amount);PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output4 sample rows
| region | quarter | amount |
|---|---|---|
| North | Q1 | 82000 |
| North | Q2 | 91000 |
| North | Q3 | 87500 |
| North | Q4 | 103000 |
Note: Illustrative unpivoted values for one region; the source may contain additional regions with four rows each.
Key takeaway: Pivot columns are fixed in SQL; dynamic sets belong in code or the BI layer.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Choose rows and columns
Decide what each output row is (a month) and which category values become columns (each status).
rows = month · columns = statusWhen to use it & trade-offs
What it is
Pivoting turns values in rows into columns, for example one row per month with a separate column for each status. In plain SQL you pivot with conditional aggregation: one SUM(CASE WHEN status = 'paid' THEN amount END) (or COUNT(*) FILTER (WHERE …)) per output column, grouped by the row dimension.
Why it matters: Reports and spreadsheets want wide tables (months down, categories across), but data is stored long (one row per event). Conditional aggregation is the portable way to reshape it in one pass, and "pivot this table" is a very common analyst interview question.
When to reach for it
- Monthly reports with categories as columns
- Comparing statuses, channels or segments side by side
- Feature tables for analysis (one row per user, one column per behaviour)
When to avoid or be careful
- Grouping by the column you're pivoting
- COUNT(CASE … ELSE 0 END), which counts every row
- Hand-writing dozens of columns for a category list that changes weekly
Conditional aggregation vs PIVOT vs pivoting in the BI tool
Strengths: Works everywhere, one scan, easy to read.
Watch out: Every category has to be written out.
Strengths: Compact syntax.
Watch out: Dialect-specific, and columns still have to be listed.
Strengths: New categories appear automatically.
Watch out: The pivot isn't available to other SQL consumers.
Interview signals & numbers to know
When this topic comes up
- “Show each status as a column”
- “Pivot / transpose this table”
- Month-by-category reports
- Wide vs long data
- Spreadsheet-style output
Benchmarks & rules of thumb
- 1
- aggregate expression per output column
- 1
- table scan for the whole pivot
- 0
- columns SQL can add on its own at run time
Common mistakes & follow-ups
Common interview mistakes
- Using COUNT(CASE WHEN … THEN 1 ELSE 0 END) and counting every row in every column.
- Adding status to GROUP BY and getting the long format back.
- Forgetting that a new category in the data won't appear until the query is changed.
Likely interviewer follow-ups
- How would you pivot when the list of categories isn't known in advance?
- How would you unpivot a table with q1–q4 columns?
- What's the difference between SUM(CASE … ELSE 0) and COUNT(CASE …)?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Pivoting Data Using Conditional Aggregation (SUM(CASE WHEN ...)) with hands-on SQL practice and interview Q&A.