Skip to content

Conditional aggregation

Put CASE or FILTER inside an aggregate to count, sum or pivot several slices of the data in one pass.

Practise: 15 questions

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:

  1. Decide the grain (the GROUP BY) and the list of output columns.
  2. For each column, write the condition that decides which rows count toward it.
  3. Put the condition inside the aggregate with CASE WHEN, which works everywhere, or FILTER (WHERE ...), which is cleaner where available.
  4. Use ELSE 0 for 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

Variations

In other warehouses

Practise conditional aggregation