When you need it
"Orders by status as separate columns", "completed versus refunded revenue side by side", "how many users did A and also B", "one column per month". Words that signal it: "as columns", "pivot", "split by", "side by side", "of which", "for each of".
Without this pattern you would run one query per slice and stitch them together. With it, one scan gives every number.
The shape of the query
select group_col,
count(*) as total,
sum(case when <condition> then <value> else 0 end) as slice_a,
count(*) filter (where <condition>) as slice_b
from ...
group by group_col;Step by step:
- Decide the grain (the
GROUP BY) and the list of output columns. - For each column, write the condition that decides which rows count toward it.
- Put the condition inside the aggregate with
CASE WHEN, which works everywhere, orFILTER (WHERE ...), which is cleaner where available. - Use
ELSE 0for sums and counts, or leave it out and let NULL be skipped.
select channel,
count(*) as orders,
count(*) filter (where status = 'completed') as completed,
count(*) filter (where status = 'refunded') as refunded,
sum(case when coupon_code is not null then 1 else 0 end) as with_coupon
from orders
group by channel
order by channel;Pivoting a category into columns uses one CASE per column:
select channel,
count(*) as tickets,
sum(case when priority = 'urgent' then 1 else 0 end) as urgent,
sum(case when priority = 'high' then 1 else 0 end) as high,
round(100.0 * sum(case when resolved_at is not null then 1 else 0 end) / count(*), 1) as pct_resolved
from tickets
group by channel
order by channel;Traps interviewers look for
COUNT(CASE WHEN ... THEN 1 ELSE 0 END).COUNTcounts non-NULL values, and0is not NULL, so this counts every row. UseSUM(...)with 1 and 0, orCOUNT(CASE WHEN ... THEN 1 END)with noELSE.SUMreturning NULL. If no row in a group matches and you have noELSE 0,SUMreturns NULL. Wrap withCOALESCE(..., 0)when the report should show zero.- Conditions in
WHEREinstead. Filtering inWHEREremoves rows from every column at once. The point here is that each column has its own filter. - Overlapping slices. A user who did both A and B counts in both columns. That is fine if the prompt expects it, wrong if the slices should add to the total. Check that the parts add up.
- Ratio denominators.
sum(case ...) / count(*)is integer division in PostgreSQL if both are integers. Multiply by100.0first. - Typos in category values.
'Completed'is not'completed'. Check the distinct values before you pivot, and add anelse 'other'bucket so rows never vanish silently.
Variations
- Pivot by month. One
CASEper month name, orsum(x) filter (where date_trunc('month', d) = ...). - Bucketing.
CASEin theSELECTto label rows ('small','medium','large') and then group by the label. - Users who did both.
count(distinct case when event = 'a' then user_id end)and the same forb, orhavingwith two conditions:having max(case when event = 'a' then 1 else 0 end) = 1 and max(case when event = 'b' then 1 else 0 end) = 1. - First or last per group by condition.
min(case when event = 'purchase' then occurred_at end)is the first purchase time, with NULL if there is none. - Weighted metrics.
sum(case when ... then amount end)oversum(amount)for a share of money, not rows.
In other warehouses
FILTER (WHERE ...)works in PostgreSQL and Databricks. Snowflake, BigQuery, SQL Server and MySQL do not have it, so writeCASE.- BigQuery has
COUNTIF(condition)andSUM(IF(cond, x, 0)). Snowflake hasCOUNT_IF(condition)andIFF(cond, a, b). - Snowflake and Databricks have a native
PIVOTclause. It is shorter, but the column list must be written out, and interviewers usually expect theCASEform. - SQL Server has
PIVOTtoo, with the same fixed column list limitation.