How do you use CASE WHEN and conditional aggregation?
Conditional aggregation puts CASE WHEN inside an aggregate, so one pass counts both all rows and only the needed ones. Without ELSE, CASE returns NULL, which the aggregate skips, so no ELSE branch is written inside COUNT: 0 is not NULL and the counter would count everything. PostgreSQL has a shorter form, FILTER (WHERE …). A percentage is multiplied by 100.0 because integer division in PostgreSQL drops the fraction.
SQL · Aggregates
A report: total, failed and the failed percentage for each transaction type. Three queries or one?
A tester checks a dashboard: for each transaction type it must show the total count, the failed count and their percentage. Three separate queries mean three passes over the table and three results that still have to be merged. Conditional aggregation does it all in one pass. This lesson is about CASE, how it works inside an aggregate, and the three traps people fall into most often.
How it works and why. CASE is an expression, not a statement: for each row it checks the WHEN conditions top to bottom and returns the THEN of the first true one. If none matched and there is no ELSE, the result is NULL. Inside an aggregate, CASE decides which value the function sees for each row. Because aggregates skip NULL, an expression without ELSE simply "switches off" the extra rows. PostgreSQL also has a shorter form for this, FILTER (WHERE …), introduced in 9.4, available in SQLite from 3.30 and absent in MySQL and SQL Server.
One pass instead of three queries
| type | status | amount |
|---|---|---|
| deposit | completed | 100 |
| deposit | failed | 50 |
| deposit | completed | 150 |
| withdrawal | failed | 20 |
| withdrawal | completed | 80 |
| type | total | failed | failed_pct |
|---|---|---|---|
| deposit | 3 | 1 | 33.3 |
| withdrawal | 2 | 1 | 50.0 |
Example: a report in one query. What the dashboard needs:
SELECT type,
COUNT(*) AS total,
COUNT(*) FILTER (WHERE status = 'failed') AS failed,
ROUND(100.0 * COUNT(*) FILTER (WHERE status = 'failed')
/ COUNT(*), 1) AS failed_pct
FROM transactions
GROUP BY type;
-- PostgreSQL; MySQL has no FILTER, see below
MySQL and SQL Server have no FILTER, so the same logic is written with CASE:
-- portable form: works everywhere
SELECT type,
SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed,
SUM(CASE WHEN status = 'completed'
THEN amount ELSE 0 END) AS completed_volume
FROM transactions
GROUP BY type;
Here ELSE 0 is deliberate: SUM then returns 0 when no row matched, while without ELSE it would return NULL. For the percentage there is one more danger. In PostgreSQL dividing two integers drops the fractional part:
-- PostgreSQL: integer division drops the fraction
SELECT 100 * 1 / 3 AS int_pct, -- 33
100.0 * 1 / 3 AS dec_pct; -- 33.3333…
So the percentage is multiplied by 100.0, not 100: the expression then becomes decimal. In MySQL the / operator returns a decimal result anyway, while PostgreSQL, SQL Server and SQLite use integer division, so code that worked in one database gives a different number in another.
A counter through CASE
COUNT(CASE … THEN 1 ELSE 0 END)
COUNT counts everything that is not NULL, and 0 is not NULL. The result equals COUNT(*): for deposit it gives 3 although only one is failed.
COUNT(CASE … THEN 1 END)
Without ELSE the extra rows give NULL and COUNT skips them. For deposit the result is 1. Or SUM(CASE … THEN 1 ELSE 0 END).
Limits and alternatives. The same CASE sorts values into categories. The order of branches matters: the first true one wins, so the narrower condition goes higher. At the edges check the boundary values (99, 100, 999, 1000):
SELECT id, amount,
CASE WHEN amount < 100 THEN 'small'
WHEN amount < 1000 THEN 'medium'
ELSE 'large' END AS bucket
FROM transactions;
-- amount = 100 → medium, amount = 1000 → large
The simple CASE status WHEN 'failed' THEN … compares only for equality, and NULL equals nothing, so a WHEN NULL branch never fires: for empty values you write WHEN status IS NULL in the searched form. Branches must give compatible types: THEN 'a' ELSE 0 fails in PostgreSQL. If the denominator can be zero (a query without GROUP BY over an empty selection, or types from a lookup table joined with LEFT JOIN and COUNT(t.id) as the denominator), protect it with NULLIF(…, 0), as in the previous lesson about NULL. A query with GROUP BY type has no empty groups.
Common mistakes.
COUNT(CASE … ELSE 0 END)instead of anELSE-less form: the counter counts all rows.- A percentage through integer division: 33 instead of 33.3 (in PostgreSQL, SQL Server, SQLite).
CASEbranches in the "wrong" order: the narrower condition is unreachable after the wider one.- A forgotten boundary in ranges:
< 100and<= 100send the amount 100 to different categories. - Dividing by a count without a zero guard: when the denominator is 0, PostgreSQL fails the query with an error, while MySQL silently returns NULL.
Check yourself
What does COUNT(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) return for a group of three transactions, one of which failed?
Answer
3. The ELSE branch gives 0, and 0 is not NULL, so COUNT counts all three rows. The right COUNT(CASE WHEN status = 'failed' THEN 1 END) gives 1, or SUM(CASE WHEN … THEN 1 ELSE 0 END).
In PostgreSQL the expression 100 * failed / total gives 33 for failed = 1 and total = 3. Why and how do you fix it?
Answer
All three values are integers, so the division is integer and drops the fraction. Multiply by 100.0 (or cast to numeric): 100.0 * 1 / 3 = 33.3333. In MySQL the / operator returns a decimal result without that.
For CASE WHEN amount < 100 THEN 'small' WHEN amount < 1000 THEN 'medium' ELSE 'large' END, which category do the amounts 100 and 1000 fall into?
Answer
100 falls into medium (amount < 100 is false and amount < 1000 is true), 1000 into large. That is why range checks take values at the boundaries: 99, 100, 999, 1000.