SQL Conditional Aggregation
What you will learn
- How to count or sum only some rows with
CASEinside an aggregate - How to compute several measures in one query
- The
FILTERclause as a shorter form - How to build a small cross table (rows to columns)
This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.
1. The idea
Sometimes one result row should show several numbers, each for a different part of the data: orders delivered, orders cancelled, orders pending. You could run three queries with different WHEREs, or put the condition inside the aggregate. CASE (lesson 2.8) gives 1 for rows that belong and 0 for the rest, and SUM adds them:
SELECT COUNT(*) AS all_orders,
SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled,
SUM(CASE WHEN status IN ('pending', 'paid', 'shipped') THEN 1 ELSE 0 END) AS in_progress
FROM orders;
all_orders delivered cancelled in_progress
---------- --------- --------- -----------
2600 1878 170 552
(1 row)
SELECT COUNT(*) AS all_rows,
SUM(CASE WHEN kind = 'deposit' THEN 1 ELSE 0 END) AS deposits,
SUM(CASE WHEN kind = 'withdrawal' THEN 1 ELSE 0 END) AS withdrawals,
SUM(CASE WHEN kind = 'fee' THEN 1 ELSE 0 END) AS fees
FROM transactions;
all_rows deposits withdrawals fees
-------- -------- ----------- ----
7415 3107 2519 403
(1 row)
SELECT COUNT(*) AS all_students,
SUM(CASE WHEN enrolled_year = 2023 THEN 1 ELSE 0 END) AS from_2023,
SUM(CASE WHEN enrolled_year = 2024 THEN 1 ELSE 0 END) AS from_2024,
SUM(CASE WHEN enrolled_year >= 2025 THEN 1 ELSE 0 END) AS from_2025_on
FROM students;
all_students from_2023 from_2024 from_2025_on
------------ --------- --------- ------------
360 83 102 175
(1 row)
This is conditional aggregation. The parts add up to the total when the groups cover every row, a good check.
2. Sums and averages of part of the data
The same pattern adds money. A CASE with no ELSE gives NULL for the other rows, and aggregates skip NULLs (lesson 3.6), so AVG(CASE ...) averages only the matching rows:
SELECT ROUND(SUM(CASE WHEN method = 'card' THEN amount ELSE 0 END), 2) AS card_total,
ROUND(SUM(CASE WHEN method <> 'card' THEN amount ELSE 0 END), 2) AS other_total,
ROUND(AVG(CASE WHEN method = 'card' THEN amount END), 2) AS card_average
FROM payments;
card_total other_total card_average
---------- ----------- ------------
126798.77 106530.12 100.47
(1 row)
SELECT SUM(CASE WHEN kind IN ('deposit', 'interest', 'transfer_in') THEN amount_cents ELSE 0 END) AS money_in_cents,
SUM(CASE WHEN kind IN ('withdrawal', 'fee', 'transfer_out') THEN amount_cents ELSE 0 END) AS money_out_cents,
ROUND(AVG(CASE WHEN kind = 'fee' THEN amount_cents END), 1) AS average_fee_cents
FROM transactions;
money_in_cents money_out_cents average_fee_cents
-------------- --------------- -----------------
107406430 45207300 560.0
(1 row)
SELECT SUM(CASE WHEN grade >= 50 THEN 1 ELSE 0 END) AS passed,
SUM(CASE WHEN grade < 50 THEN 1 ELSE 0 END) AS failed,
ROUND(AVG(CASE WHEN grade >= 50 THEN grade END), 1) AS average_of_passed
FROM enrollments;
passed failed average_of_passed
------ ------ -----------------
757 52 73.1
(1 row)
(The pass mark of 50 is made up. Enrollments with no grade yet are in neither group, because a comparison with NULL is not true.)
3. FILTER: a shorter way
SQLite (version 3.30 and later) and some other databases support the standard FILTER clause, which says the same thing more directly:
SELECT COUNT(*) AS all_orders,
COUNT(*) FILTER (WHERE status = 'delivered') AS delivered,
COUNT(*) FILTER (WHERE status = 'cancelled') AS cancelled
FROM orders;
all_orders delivered cancelled
---------- --------- ---------
2600 1878 170
(1 row)
SELECT COUNT(*) AS all_rows,
COUNT(*) FILTER (WHERE kind = 'deposit') AS deposits,
SUM(amount_cents) FILTER (WHERE kind = 'fee') AS fee_cents
FROM transactions;
all_rows deposits fee_cents
-------- -------- ---------
7415 3107 225700
(1 row)
SELECT COUNT(*) AS all_students,
COUNT(*) FILTER (WHERE enrolled_year = 2024) AS from_2024,
COUNT(*) FILTER (WHERE guardian_name IS NULL) AS without_guardian
FROM students;
all_students from_2024 without_guardian
------------ --------- ----------------
360 102 38
(1 row)
FILTER (WHERE ...) after an aggregate keeps only the matching rows for that aggregate. Not every database supports it (MySQL's documentation page on aggregate functions shows no FILTER clause), but CASE works everywhere, so learn CASE first and FILTER as a convenience.
4. A small cross table
Conditional aggregation can turn the values of a column into columns of the result, for a table with groups down the side and categories across the top. Group by the rows, and use one SUM(CASE ...) for each column:
Orders per year of order date, split by delivered and cancelled:
SELECT SUBSTR(order_date, 1, 4) AS year,
SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled,
COUNT(*) AS all_orders
FROM orders GROUP BY SUBSTR(order_date, 1, 4) ORDER BY year;
year delivered cancelled all_orders
---- --------- --------- ----------
2024 354 33 485
2025 705 75 965
2026 819 62 1150
(3 rows)
Accounts per type, split by status:
SELECT account_type,
SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) AS open,
SUM(CASE WHEN status = 'frozen' THEN 1 ELSE 0 END) AS frozen,
SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) AS closed
FROM accounts GROUP BY account_type ORDER BY account_type;
account_type open frozen closed
------------ ---- ------ ------
checking 284 11 21
savings 120 5 9
(2 rows)
Students per year of enrolment, split by whether a guardian is recorded:
SELECT enrolled_year,
SUM(CASE WHEN guardian_name IS NOT NULL THEN 1 ELSE 0 END) AS with_guardian,
SUM(CASE WHEN guardian_name IS NULL THEN 1 ELSE 0 END) AS without_guardian
FROM students GROUP BY enrolled_year ORDER BY enrolled_year;
enrolled_year with_guardian without_guardian
------------- ------------- ----------------
2023 73 10
2024 93 9
2025 78 8
2026 78 11
(4 rows)
Worked example: a status report in one query
A manager wants one line: total orders, how many delivered, how many cancelled, and the share cancelled.
| Column | Expression |
|---|---|
| total | COUNT(*) |
| delivered | SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) |
| cancelled | SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) |
| share cancelled | ROUND(100.0 * SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) / COUNT(*), 1) |
One pass over the table gives all four numbers. The table is made up.
Common mistakes
- Writing
COUNT(CASE WHEN ... THEN 1 ELSE 0 END).COUNTcounts every non-NULLvalue, including the zeros; useSUM, or leave out theELSE. - Groups that overlap or leave rows out, so the parts do not add up.
- Forgetting that rows with
NULLfail both>=and<. - Using
FILTERin a database that does not support it.
Key takeaways
SUM(CASE WHEN cond THEN 1 ELSE 0 END)counts the rows that meetcond;SUM(CASE WHEN cond THEN x ELSE 0 END)addsxfor them.- A
CASEwithoutELSEgivesNULL, which aggregates skip, soAVG(CASE ...)averages only the matching rows. FILTER (WHERE ...)is a shorter standard form.- Combining
GROUP BYwith several conditional sums builds a small cross table.
Practice
1. Write a column that counts the rows where price > 20.
Show answer
SUM(CASE WHEN price > 20 THEN 1 ELSE 0 END)
2. Why is COUNT(CASE WHEN x > 5 THEN 1 ELSE 0 END) wrong?
Show answer
COUNT counts every non-NULL value, and 0 is not NULL, so it counts all rows. Use SUM, or COUNT(CASE WHEN x > 5 THEN 1 END).
3. What does AVG(CASE WHEN kind = 'fee' THEN amount END) average?
Show answer
Only the amounts of the fee rows; the other rows give NULL, which AVG skips.
4. Rewrite SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) with FILTER.
Show answer
COUNT(*) FILTER (WHERE status = 'open')
5. How can you check that conditional groups cover every row?
Show answer
Add the groups together and compare with COUNT(*).
6. Where do the groups go in a cross table, and where do the categories go?
Show answer
The groups are the rows (the GROUP BY column) and the categories become columns (one SUM(CASE ...) each).