Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 26/ 160
02. Aggregations, Functions & Data Manipulation

Pivoting Data Using Conditional Aggregation (SUM(CASE WHEN ...))

Pivot categories into columns with SUM/COUNT(CASE WHEN ...) patterns.

IntermediateConditional SUM · Pivot Pattern3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Revenue by category across, months downQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  date_trunc('month', o.created_at) AS MONTH,3  SUM(4    CASE5      WHEN p.category = 'books' THEN o.amount6      ELSE 07    END8  ) AS books,9  SUM(10    CASE11      WHEN p.category = 'toys' THEN o.amount12      ELSE 013    END14  ) AS toys15FROM16  orders o17  JOIN products p ON p.id = o.product_id18GROUP BY19  1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/19
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output3 sample rows
Expected output
monthbookstoys
2026-09-01128009400
2026-10-011515011200
2026-11-0168005250

Note: Illustrative monthly category totals in currency units.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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).

Unpivoting quarterly columns (PostgreSQL)Query example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  s.region,3  v.quarter,4  v.amount5FROM6  sales_wide s7  CROSS JOIN LATERAL (8    VALUES9      ('Q1', s.q1),10      ('Q2', s.q2),11      ('Q3', s.q3),12      ('Q4', s.q4)13  ) AS v (quarter, amount);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/13
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
regionquarteramount
NorthQ182000
NorthQ291000
NorthQ387500
NorthQ4103000

Note: Illustrative unpivoted values for one region; the source may contain additional regions with four rows each.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Pivot columns are fixed in SQL; dynamic sets belong in code or the BI layer.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Choose rows and columns

Decide what each output row is (a month) and which category values become columns (each status).

SQL at this stepReadable preview
1rows = month · columns = status
What to watch at this step
Columns
known in advance
Tip: use ← → to move between steps

When 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

SUM / COUNT over CASE or FILTER
Best for: Portable SQL with a known set of columns

Strengths: Works everywhere, one scan, easy to read.

Watch out: Every category has to be written out.

PIVOT operator / crosstab()
Best for: SQL Server, Oracle, or PostgreSQL with tablefunc

Strengths: Compact syntax.

Watch out: Dialect-specific, and columns still have to be listed.

Return long data, pivot in BI
Best for: Categories that change often

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 …)?
Interview tip: Write one column fully, then say "the others follow the same pattern". Mentioning FILTER and the dynamic-columns limitation shows depth without extra typing.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Conditional Logic with CASE WHEN ... THEN ... ELSE ... END
Next topic
NULL Handling Functions (COALESCE, NULLIF, IFNULL)