Sub topic 2
The Classic Approach: `CASE` Inside an Aggregate
This chapter assumes that you know basic SELECT, WHERE, and ORDER BY, and that you have used aggregates such as count, sum, and avg. You should also understand that SQL NULL means “missing or unknown,” and that many aggregates ignore NULL values.
Conditional aggregation calculates a value from only the rows that meet a condition. Before PostgreSQL supported the FILTER clause, the usual technique was to put a CASE expression inside the aggregate function.
How the pattern works
A CASE expression chooses a result for each input row. For example:
CASE
WHEN status = 'refunded' THEN 1
ENDFor a refunded order, this expression returns 1. For every other order, it returns NULL because no ELSE branch exists.
The aggregate then processes those results. Since count(expression) counts only non-NULL values, it counts refunded orders:
SELECT
count(
CASE
WHEN status = 'refunded' THEN 1
END
) AS refunded_orders
FROM orders;The database evaluates the expression for every row, then counts the returned 1 values.
The same idea works with other aggregates. To total the amount of paid orders, return amount for paid rows and NULL otherwise:
SELECT
sum(
CASE
WHEN status = 'paid' THEN amount
END
) AS paid_revenue
FROM orders;For each row, the CASE expression produces either the order amount or NULL. sum ignores the NULL results and adds the paid amounts.
Counting and summing safely
A common mistake is using count(*) around a CASE expression:
SELECT count(*) AS refunded_orders
FROM orders
WHERE status = 'refunded';This query is valid, but it filters out all other rows before aggregation. That can be useful when you need only refunded orders. It is less useful when one query must calculate several different conditions.
Instead, use separate conditional expressions:
SELECT
count(CASE WHEN status = 'paid' THEN 1 END) AS paid_orders,
count(CASE WHEN status = 'refunded' THEN 1 END) AS refunded_orders,
sum(CASE WHEN status = 'paid' THEN amount END) AS paid_revenue
FROM orders;All rows reach the aggregate step. Each CASE expression decides independently whether its row contributes.
| Expression | Matching row | Nonmatching row | Aggregate result |
|---|---|---|---|
| `CASE WHEN ... THEN 1 END` | `1` | `NULL` | Count matching rows |
| `CASE WHEN ... THEN amount END` | Amount | `NULL` | Sum matching amounts |
You can also provide an ELSE branch:
SELECT
sum(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid_revenue
FROM orders;For sum, ELSE 0 often produces the same total as an omitted ELSE, because sum ignores NULL. However, the result differs when no rows match. The version without ELSE returns NULL; the version with ELSE 0 returns zero.
For counting, ELSE 0 is usually incorrect:
SELECT count(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END)
FROM orders;count(expression) counts every non-NULL value. Both 1 and 0 are non-NULL, so this counts every order, not only refunded orders. Use ELSE NULL, or omit ELSE, when you want count to ignore nonmatching rows.
Conditional aggregation by group
Add GROUP BY when you need one result per group. This example calculates paid and refunded orders for each customer:
SELECT
customer_id,
count(CASE WHEN status = 'paid' THEN 1 END) AS paid_orders,
count(CASE WHEN status = 'refunded' THEN 1 END) AS refunded_orders,
sum(CASE WHEN status = 'paid' THEN amount END) AS paid_revenue
FROM orders
GROUP BY customer_id
ORDER BY customer_id;The database forms one group for each customer_id. Inside each group, every CASE expression examines the rows independently.
The CASE pattern is portable across many SQL databases and remains useful when working with systems that do not support PostgreSQL’s FILTER syntax. Its main cost is readability: the condition is embedded inside every aggregate expression, so a report with many conditions can become repetitive.
Exercise
Why does count(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) count every row?
Show answer
Both 1 and 0 are non-NULL values, so count(expression) includes every row. Omit ELSE or return NULL for nonmatching rows.