Sub topic 2
The Classic Approach: CASE Inside an Aggregate
This chapter assumes you can write SELECT, WHERE and GROUP BY queries and have used count, sum and avg. It also assumes you know that a comparison with NULL is neither true nor false. Every example uses the orders table from the previous chapter. The status values are 'paid', 'refunded' and 'pending'.
Before PostgreSQL had FILTER (added in version 9.4), people computed conditional totals by putting a CASE expression inside an aggregate. You will still meet this pattern in older code, in other databases and in tutorials. It also explains what FILTER does, so it is worth learning well.
The problem it solves
A WHERE clause removes rows before any aggregate runs. That is a problem when one report needs several different subsets. You might want all orders, only refunded orders and only paid revenue, side by side in a single row. Three separate queries would scan the table three times and give you three result sets to stitch together.
The goal is one query where each aggregate sees only the rows it cares about. Here is a small data set to follow along with:
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
amount numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL
);
INSERT INTO orders (id, customer_id, status, amount, created_at) VALUES
(1, 10, 'paid', 40.00, '2026-01-05 10:00+00'),
(2, 10, 'refunded', 25.00, '2026-01-09 12:00+00'),
(3, 11, 'paid', 120.00, '2026-01-20 09:30+00'),
(4, 12, 'pending', 60.00, '2026-02-02 14:00+00'),
(5, 11, 'paid', 80.00, '2026-02-11 16:45+00'),
(6, 12, 'refunded', 30.00, '2026-02-15 08:15+00');Two facts the pattern depends on
The technique rests on two facts. Learn both and the rest of the chapter follows from them.
- A
CASEexpression with noELSEbranch returnsNULLwhen noWHENcondition is true. - Most aggregate functions ignore
NULLinputs.sum,avg,min,maxandcount(expression)all skip them.
Combine the two. If CASE returns the value you want for matching rows and NULL for every other row, the aggregate effectively sees only the matching rows.
count(*) is the exception to the second fact. It counts rows, not values, so it never skips anything. count(expression) counts only the rows where the expression is not NULL.
Counting matching rows
To count refunded orders, make CASE return any non-NULL constant for refunded rows. The constant 1 is the usual choice, because the value itself never matters. Only whether it is NULL matters.
SELECT
count(*) AS total_orders,
count(CASE WHEN status = 'refunded' THEN 1 END) AS refunded_orders
FROM orders;With the sample data this returns 6 and 2. The first aggregate counts every row. The second receives NULL for four rows and 1 for two rows, so it counts 2.
Summing matching values
For sums, let CASE return the column you want to add up:
SELECT
count(CASE WHEN status = 'refunded' THEN 1 END) AS refunded_orders,
sum(CASE WHEN status = 'paid' THEN amount END) AS paid_revenue
FROM orders;The result is 2 refunded orders and 240.00 in paid revenue (40 + 120 + 80). Each aggregate in the same SELECT list has its own CASE, so each one applies its own condition. All of them run over the same scan of the table.
Counting distinct values and buckets
Because CASE is an ordinary expression, it works anywhere an expression does. That includes DISTINCT:
SELECT
count(DISTINCT CASE WHEN status = 'refunded' THEN customer_id END) AS customers_with_refunds
FROM orders;This counts each customer once, however many refunds they have. Customers 10 and 12 each have one refund, so the result is 2.
You can also use several WHEN branches. This is how the pattern builds buckets, with each aggregate counting one range:
SELECT
count(CASE WHEN amount < 50 THEN 1 END) AS small_orders,
count(CASE WHEN amount >= 50 AND amount < 100 THEN 1 END) AS medium_orders,
count(CASE WHEN amount >= 100 THEN 1 END) AS large_orders
FROM orders;For the sample data this gives 3, 2 and 1. The ranges are written so that every order lands in exactly one of them.
Grouped reports
The same pattern works inside GROUP BY. The conditional aggregates are computed separately for each group:
SELECT
date_trunc('month', created_at) AS month,
count(*) AS orders,
count(CASE WHEN status = 'paid' THEN 1 END) AS paid_orders,
sum(CASE WHEN status = 'paid' THEN amount END) AS paid_revenue,
count(CASE WHEN status = 'refunded' THEN 1 END) AS refunded_orders
FROM orders
GROUP BY 1
ORDER BY 1;The result has one row per month:
| month | orders | paid_orders | paid_revenue | refunded_orders |
|---|---|---|---|---|
| 2026-01-01 | 3 | 2 | 160.00 | 1 |
| 2026-02-01 | 3 | 1 | 80.00 | 1 |
Reports that turn the values of one column into several output columns are often called pivots or cross-tabs. Writing one CASE aggregate per value is the standard way to build them in plain SQL.
The ELSE trap
The most common mistake with this pattern is adding an ELSE 0. It looks harmless and even tidy. For counting, it breaks the query:
SELECT
count(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS wrong_count
FROM orders;This returns 6, not 2. Every row now produces either 1 or 0, and neither is NULL, so count counts all of them. The aggregate no longer skips anything.
There are two correct ways to count with an ELSE. The first is to drop the ELSE and let the NULL do the work, as shown earlier. The second is to keep ELSE 0 and use sum instead, which adds the ones and zeros:
SELECT
sum(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS refunded_orders
FROM orders;This returns 2. Both forms are valid, but do not mix count with ELSE 0. Keep in mind that sum returns bigint for integer input, while count also returns bigint, so the types agree.
The trap is worse with avg. Here ELSE 0 changes the meaning of the result:
SELECT
avg(CASE WHEN status = 'paid' THEN amount END) AS avg_paid_order,
avg(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS diluted_average
FROM orders;The first column is 80.00, the average of the three paid orders. The second is 40.00, because the three non-paid rows now count as zeros in the denominator. Both queries run without error, and only one answers the question you asked. For avg, min and max, leave out the ELSE.
Empty row sets: count returns 0, sum returns NULL
If no row matches, the aggregates behave differently. count returns 0. sum, avg, min and max return NULL, because they received no values at all.
SELECT
count(CASE WHEN status = 'cancelled' THEN 1 END) AS cancelled_orders,
sum(CASE WHEN status = 'cancelled' THEN amount END) AS cancelled_revenue
FROM orders;This returns 0 and NULL. A report that must show zero can wrap the aggregate in coalesce(..., 0). A later chapter covers this in detail.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `count` returns the total number of rows | The `CASE` has `ELSE 0` or another non-`NULL` fallback | Remove the `ELSE`, or switch to `sum(... THEN 1 ELSE 0 END)` |
| An average is lower than expected | `ELSE 0` adds zero values to the average | Remove the `ELSE` so non-matching rows become `NULL` |
| A percentage is always 0 or 100 | Integer division, as in `count(...) / count(*)` | Multiply by `100.0` first, as in `100.0 * count(...) / count(*)` |
| An error about invalid input syntax for a type | `THEN` and `ELSE` return incompatible types, such as `THEN 1 ELSE 'none'` | Make every branch return the same type, or omit the `ELSE` |
| A row you expected to match is missed | The condition evaluates to `NULL`, for example `status = NULL` on a nullable column | Use `IS NULL` or `IS NOT NULL` for `NULL` tests |
The last row deserves a note. A WHEN branch fires only when its condition is true. If the condition is unknown, which is what any comparison with NULL produces, the CASE moves on to the next branch or the ELSE. In our table status is declared NOT NULL, so this cannot happen there. It matters for nullable columns.
Where this pattern is weak
The pattern works, but it has costs that you can see in the examples above.
- Readability. The condition and the aggregated value are tangled together. In
sum(CASE WHEN status = 'paid' THEN amount END), you have to read the whole expression to see that the point is "sum amount where paid". - Silent mistakes. An
ELSEbranch in the wrong place changes the result without any error, as thecountandavgexamples showed. - Longer queries. A report with ten conditional columns repeats
CASE WHEN ... THEN ... ENDten times.
PostgreSQL's FILTER clause removes these problems by moving the condition out of the expression. The next chapter introduces it. Since the two approaches give the same results, anything you learned here carries over directly.
Summary
- A
CASEwithoutELSEreturnsNULLfor non-matching rows, and most aggregates skipNULL. - Use
count(CASE WHEN cond THEN 1 END)to count matching rows andsum(CASE WHEN cond THEN col END)to total a column over them. - Never add
ELSE 0to aCASEinsidecount,avg,minormax. - When no rows match,
countreturns0and the other aggregates returnNULL.
Exercise
Using the orders table, write one query that returns, for each customer_id, the number of paid orders and the average amount of refunded orders. Use only CASE inside the aggregates. What value does the average column hold for a customer who has no refunded orders, and why?
Show answer
SELECT customerid, count(CASE WHEN status = 'paid' THEN 1 END) AS paidorders, avg(CASE WHEN status = 'refunded' THEN amount END) AS avgrefund FROM orders GROUP BY customerid ORDER BY customerid; For a customer with no refunded orders, avgrefund is NULL. The CASE returns NULL for every row in that group, so avg receives no values and returns NULL. For the sample data, customer 11 has two paid orders and a NULL average, customer 10 has one paid order and an average refund of 25.00, and customer 12 has zero paid orders and an average refund of 30.00.
Exercise
A colleague wrote count(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_orders and gets 6 on the sample data instead of 3. Explain the cause and give two different fixes.
Show answer
The ELSE 0 makes every row produce a non-NULL value (1 or 0), and count counts every non-NULL value, so all 6 rows are counted. Fix 1: remove the ELSE, giving count(CASE WHEN status = 'paid' THEN 1 END), so non-matching rows produce NULL and are skipped. Fix 2: keep the ELSE 0 and use sum instead, giving sum(CASE WHEN status = 'paid' THEN 1 ELSE 0 END). Both return 3.
Exercise
Write a query that returns the percentage of orders that are refunded, rounded to one decimal place, using CASE inside the aggregate. Why must the query use 100.0 rather than 100?
Show answer
SELECT round(100.0 count(CASE WHEN status = 'refunded' THEN 1 END) / count(), 1) AS refund_pct FROM orders; The result is 33.3. With 100, the multiplication and division would use integers, so 100 2 / 6 would be integer division and give 33 with the decimals lost. With 100.0 the expression is computed as numeric, which keeps the fraction. Note that count() is never 0 here unless the table is empty, in which case the division would raise a division by zero error.