Sub topic 4
FILTER versus CASE: same results, different readability
This chapter assumes you can write GROUP BY queries and know that count, sum and avg skip NULL inputs. It also assumes you have seen conditional aggregation written with CASE, as in the previous chapters. All examples use the orders table from the start of the tutorial.
For most queries, FILTER and CASE inside an aggregate return identical results. They differ in a few edge cases, and those cases decide which one is correct for your query. They also differ in how easy the query is to read.
The same query, written both ways
Here is a query that counts refunded orders and sums paid revenue, first with CASE:
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;Here is the same query with FILTER:
SELECT
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders;Both versions work in a single pass over the table. The CASE version passes NULL to the aggregate for rows that do not match, and the aggregate skips NULLs. The FILTER version never hands non-matching rows to the aggregate at all. The effect is the same, but the mechanism differs, and that is where the edge cases come from.
Translation rules
The conversion is mechanical when the CASE has one branch and no ELSE.
| CASE form | FILTER form |
|---|---|
| `count(CASE WHEN c THEN 1 END)` | `count(*) FILTER (WHERE c)` |
| `count(CASE WHEN c THEN x END)` | `count(x) FILTER (WHERE c)` |
| `sum(CASE WHEN c THEN x END)` | `sum(x) FILTER (WHERE c)` |
| `avg(CASE WHEN c THEN x END)` | `avg(x) FILTER (WHERE c)` |
| `max(CASE WHEN c THEN x END)` | `max(x) FILTER (WHERE c)` |
| `count(DISTINCT CASE WHEN c THEN x END)` | `count(DISTINCT x) FILTER (WHERE c)` |
Notice the second row. count(CASE WHEN c THEN x END) counts rows where the condition holds and x is not NULL. count(*) FILTER (WHERE c) counts every row where the condition holds, even if x is NULL. To get the exact CASE behavior, write count(x) FILTER (WHERE c). Choose deliberately which one you mean.
Where the two diverge
The ELSE 0 trap with count
A common mistake is to copy a sum pattern into count:
SELECT
count(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS wrong_refunds,
count(*) AS total_orders
FROM orders;count(expr) counts non-NULL values. The expression returns 1 or 0, and neither is NULL, so wrong_refunds equals total_orders. The FILTER form has no ELSE branch to get wrong, so the mistake cannot happen.
ELSE 0 changes sum and avg
For sum, adding ELSE 0 is harmless to the total, but it changes what happens when no row matches. This query makes the difference visible with inline data:
WITH o(status, amount) AS (
VALUES ('refunded', 5.00), ('refunded', 7.00)
)
SELECT
sum(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS case_else_zero,
sum(CASE WHEN status = 'paid' THEN amount END) AS case_no_else,
sum(amount) FILTER (WHERE status = 'paid') AS filter_sum
FROM o;The result is 0, NULL and NULL. The ELSE 0 version reports zero revenue, while the other two report that there was nothing to add up. Whether that distinction matters depends on the report. The next chapter section on NULLs covers it in detail. If you want zero, wrap the aggregate in coalesce instead of relying on ELSE 0, so the intent is visible.
With avg, ELSE 0 is a real bug. The zeros are included in the average:
SELECT
avg(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS diluted_avg,
avg(amount) FILTER (WHERE status = 'paid') AS paid_avg
FROM orders;diluted_avg divides paid revenue by all orders. paid_avg divides it by paid orders only. The same applies to min, where ELSE 0 would return 0 whenever any row fails the condition and all amounts are positive.
array_agg keeps NULLs
array_agg is the aggregate where the two forms visibly differ even without an ELSE. Unlike sum or string_agg, it does not skip NULL inputs:
WITH o(id, status) AS (
VALUES (1, 'paid'), (2, 'refunded'), (3, 'paid')
)
SELECT
array_agg(CASE WHEN status = 'paid' THEN id END) AS with_case,
array_agg(id) FILTER (WHERE status = 'paid') AS with_filter
FROM o;with_case is {1,NULL,3} and with_filter is {1,3}. The CASE version injects a NULL for every non-matching row. If you rewrite old CASE code to FILTER for an array aggregate, check whether anything downstream depended on those NULLs. Usually nothing did, and the FILTER result is what the author wanted.
Different values per condition
CASE can choose different expressions for different conditions. FILTER can only decide whether a row participates. A net revenue figure that adds paid orders and subtracts refunds is naturally a CASE:
SELECT
sum(
CASE status
WHEN 'paid' THEN amount
WHEN 'refunded' THEN -amount
END
) AS net_revenue
FROM orders;You can express this with two FILTER aggregates, but you must subtract them yourself and handle NULLs:
SELECT
coalesce(sum(amount) FILTER (WHERE status = 'paid'), 0)
- coalesce(sum(amount) FILTER (WHERE status = 'refunded'), 0) AS net_revenue
FROM orders;The CASE form is shorter here. When the value being aggregated changes with the condition, prefer CASE.
Readability
FILTER separates two questions: what to aggregate, and which rows to include. In sum(amount) FILTER (WHERE status = 'paid') the aggregated expression is amount, and the condition is a separate clause. In the CASE form both are mixed inside one expression, and the reader has to find the THEN branch to learn what is being summed.
The difference grows with the number of columns. In a report with eight conditional columns and several conditions each, FILTER lines up as a column of aggregate FILTER (WHERE ...) patterns. A reader can scan the left side for what is measured and the right side for the condition.
CASE has its own advantage: it is a general expression, so you already know it. It also appears in every SQL database, and FILTER does not.
Portability
FILTER is part of the SQL standard and PostgreSQL has supported it since version 9.4. SQLite supports it from version 3.30. MySQL and SQL Server do not support it, so a query that must run on those systems has to use CASE. If your queries only target PostgreSQL, portability is not a reason to choose CASE.
Performance
In PostgreSQL, both forms are evaluated inside the same aggregate plan node. The table is scanned once, and each aggregate has its own condition evaluated per row. You should not expect a meaningful speed difference between them. Do not rewrite working queries for speed alone. If you suspect a difference, compare the plans:
EXPLAIN (ANALYZE, VERBOSE)
SELECT
count(*) FILTER (WHERE status = 'refunded'),
sum(amount) FILTER (WHERE status = 'paid')
FROM orders;Run the same statement with the CASE version and compare the execution times and the Output lines. A later chapter covers reading plans for these queries.
Choosing between them
As a default in PostgreSQL code, use FILTER. Use CASE when the value changes per condition or when the query must stay portable.
Rewriting an existing query
Take a monthly report written the older way:
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
FROM orders
GROUP BY 1
ORDER BY 1;Apply the translation rules one aggregate at a time. count(*) has no condition, so it stays. The next two become:
SELECT
date_trunc('month', created_at) AS month,
count(*) AS orders,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders
GROUP BY 1
ORDER BY 1;The result is the same, because no ELSE branch was present and amount is declared NOT NULL. Before converting any query, check for three things: an ELSE with a non-NULL value, an aggregate that keeps NULLs such as array_agg, and a column that can be NULL under count(x).
Exercise
A colleague writes avg(CASE WHEN status = 'paid' THEN amount ELSE 0 END) to get the average paid order. Explain what the query actually computes and write the correct version with FILTER.
Show answer
The query averages amount for paid orders and 0 for every other order, so the divisor is the total number of orders and the result is too low. The correct version is avg(amount) FILTER (WHERE status = 'paid'), which only averages paid orders.
Exercise
You convert array_agg(CASE WHEN status = 'refunded' THEN id END) to array_agg(id) FILTER (WHERE status = 'refunded'). For a customer with orders 1 (paid), 2 (refunded) and 3 (paid), what does each version return, and what does the FILTER version return for a customer with no refunds?
Show answer
The CASE version returns {NULL,2,NULL} because array_agg keeps NULL inputs. The FILTER version returns {2}. For a customer with no refunds, the FILTER version returns NULL, because no row reached the aggregate, while the CASE version returns an array made only of NULLs.