CASE WHEN in aggregates
Concepts covered: Conditional Aggregation
COUNT_IF counts. Most bucketed questions need more than a count: listening time per genre, the average length of full plays only, revenue split by channel. The general tool is a CASE expression inside the aggregate. CASE runs first and, for each row, turns the value into what the bucket should receive. The aggregate then does its usual work on whatever CASE handed it.
SELECT
listener_id,
SUM(CASE WHEN genre = 'pop' THEN ms_played ELSE 0 END) AS pop_ms,
SUM(CASE WHEN genre = 'rock' THEN ms_played ELSE 0 END) AS rock_ms,
SUM(CASE WHEN genre = 'jazz' THEN ms_played ELSE 0 END) AS jazz_ms
FROM plays
GROUP BY listener_id
ORDER BY listener_id| listener_id | track | genre | played_at | ms_played | skipped |
|---|---|---|---|---|---|
| ana | Aurora | pop | 08:10 | 200000 | 0 |
| ana | Basalt | rock | 08:14 | 15000 | 1 |
| ana | Cinder | rock | 08:20 | 240000 | 0 |
| ana | Aurora | pop | 09:02 | 198000 | 0 |
| ben | Delta | jazz | 07:45 | 310000 | 0 |
| ben | Ember | pop | 07:51 | 9000 | 1 |
| ben | Fjord | jazz | 08:30 | 12000 | 1 |
| cy | Basalt | rock | 10:00 | 230000 | 0 |
| listener_id | pop_ms | rock_ms | jazz_ms |
|---|---|---|---|
| ana | 398000 | 255000 | 0 |
| ben | 9000 | 0 | 322000 |
| cy | 0 | 230000 | 0 |
Each of the 3 SUMs sees all of a listener's rows. For pop_ms, a pop row contributes its ms_played and every other row contributes 0, so ana's pop column adds 200000 and 198000 into 398000 and ignores her rock plays. A single scan and a single GROUP BY have split each listener's total into 3 columns. This layout, values of a category turned into fixed columns, is called a pivot.
ELSE 0 or no ELSE
A CASE without ELSE returns NULL for rows that match no branch, and SUM and AVG skip those NULLs, as do MIN and MAX. For SUM the 2 spellings agree whenever at least 1 row matches, since adding 0 changes nothing; if no row matches, ELSE 0 returns 0 and the bare CASE returns NULL. For AVG they split: ELSE 0 puts the non-matching rows into the denominator as zeros, while leaving ELSE out removes those rows from the average.
SELECT
department,
SUM(CASE WHEN is_manager THEN salary ELSE 0 END) AS manager_payroll,
AVG(CASE WHEN tenure_years >= 5 THEN salary END) AS avg_senior_salary
FROM employee_metrics
GROUP BY department| department | salary | is_manager | tenure_years |
|---|---|---|---|
| Sales | 80000 | 1 | 6 |
| Sales | 50000 | 0 | 5 |
| Eng | 90000 | 0 | 7 |
| Eng | 70000 | 1 | 3 |
Follow Eng through the animation. Its manager earns 70000 and its other engineer 90000, so manager_payroll adds 70000 and 0 and lands on 70000. For avg_senior_salary only the 7-year engineer passes tenure_years >= 5; the 3-year manager's CASE yields NULL, which AVG skips, so the result is 90000. Had the CASE ended in ELSE 0, AVG would have averaged 90000 with 0 and reported 45000, half of what Eng's only senior earns. In Sales both employees have 5 or more years, so its average is 65000 either way.
A teammate wants each listener's number of skipped plays and writes the query below. What does skips hold for ana, who has 4 plays and 1 skip?
SELECT
listener_id,
COUNT(CASE WHEN skipped THEN 1 ELSE 0 END) AS skips
FROM plays
GROUP BY listener_id- 1, because the CASE returns 1 only for her single skipped play
- 0, because COUNT passes over the 0 values that CASE returns
- 4, because COUNT counts every non-NULL value and 0 is not NULL
- 3, because COUNT subtracts the rows where the CASE returned 0
Buckets as rows or as columns
CASE can also sit in GROUP BY, where it decides which group a row joins instead of what it contributes. The same split, plays under 30 seconds against the rest, comes out as 2 rows that way, and as 2 columns when each CASE sits inside its own aggregate.
| listener_id | track | genre | played_at | ms_played | skipped |
|---|---|---|---|---|---|
| ana | Aurora | pop | 08:10 | 200000 | 0 |
| ana | Basalt | rock | 08:14 | 15000 | 1 |
| ana | Cinder | rock | 08:20 | 240000 | 0 |
| ana | Aurora | pop | 09:02 | 198000 | 0 |
| ben | Delta | jazz | 07:45 | 310000 | 0 |
| ben | Ember | pop | 07:51 | 9000 | 1 |
| ben | Fjord | jazz | 08:30 | 12000 | 1 |
| cy | Basalt | rock | 10:00 | 230000 | 0 |
As rows
CASE labels each row, GROUP BY makes a group per label, and the output has a row per bucket.
SELECT
CASE WHEN ms_played < 30000 THEN 'under 30s' ELSE '30s or more' END AS length_bucket,
COUNT(*) AS play_count
FROM plays
GROUP BY 1
ORDER BY length_bucket| length_bucket | play_count |
|---|---|
| 30s or more | 5 |
| under 30s | 3 |
As columns
Each SUM receives 1 or 0 from its own CASE, and the output is a single row with a column per bucket.
SELECT
SUM(CASE WHEN ms_played < 30000 THEN 1 ELSE 0 END) AS under_30s,
SUM(CASE WHEN ms_played >= 30000 THEN 1 ELSE 0 END) AS at_least_30s
FROM plays| under_30s | at_least_30s |
|---|---|
| 3 | 5 |
- CASE in GROUP BY (rows)
- A row per bucket in the output
- Buckets are values, so 10 buckets still fit in 2 columns
- Each row lands in exactly 1 bucket: the first branch it matches
- Suits a chart or a further aggregation
- CASE in the aggregate (columns)
- A column per bucket in the output
- Each bucket is a column you write by hand
- A row can count toward several overlapping buckets
- Suits a report row beside other per-listener figures
Collecting into a bucket
CASE also works inside the aggregates from the first sections, with a trap. ARRAY_AGG(CASE WHEN skipped THEN track END) hands the array a NULL for every unskipped play, because ARRAY_AGG keeps NULLs, so ana's array would hold Basalt plus 3 NULLs. The FILTER clause from the COUNT_IF section removes rows before the aggregate sees them, which is the shape you want for collecting.
SELECT
listener_id,
ARRAY_AGG(track ORDER BY played_at) FILTER (WHERE skipped) AS skipped_tracks,
SUM(CASE WHEN skipped THEN ms_played ELSE 0 END) AS skipped_ms
FROM plays
GROUP BY listener_id
ORDER BY listener_id| listener_id | track | genre | played_at | ms_played | skipped |
|---|---|---|---|---|---|
| ana | Aurora | pop | 08:10 | 200000 | 0 |
| ana | Basalt | rock | 08:14 | 15000 | 1 |
| ana | Cinder | rock | 08:20 | 240000 | 0 |
| ana | Aurora | pop | 09:02 | 198000 | 0 |
| ben | Delta | jazz | 07:45 | 310000 | 0 |
| ben | Ember | pop | 07:51 | 9000 | 1 |
| ben | Fjord | jazz | 08:30 | 12000 | 1 |
| cy | Basalt | rock | 10:00 | 230000 | 0 |
| listener_id | skipped_tracks | skipped_ms |
|---|---|---|
| ana | ["Basalt"] | 15000 |
| ben | ["Ember","Fjord"] | 21000 |
| cy | NULL | 0 |
ana's skipped list is Basalt, worth 15000 ms; ben's is Ember then Fjord, worth 21000 ms. cy skipped nothing, so the FILTER leaves ARRAY_AGG no rows and it returns NULL, while the SUM over CASE still reports 0 because every one of cy's rows handed it a 0.
- Do
- Write ELSE 0 inside SUM so a bucket with no matching rows reads 0
- Leave ELSE out inside AVG so non-matching rows stay out of the denominator
- Count a bucket with COUNT_IF or SUM(CASE WHEN ... THEN 1 ELSE 0 END)
- Name each bucket column after its condition, such as under_30s
- Avoid
- Don't wrap a CASE that ends in ELSE 0 in COUNT; it counts every row
- Don't add ELSE 0 to an AVG unless zeros belong in the average
- Don't write overlapping branches in a GROUP BY CASE; the first match wins
- Don't pivot categories that change weekly into columns; collect them with MAP_AGG
About this lesson
This section is part of the Aggregating: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.