Sub topic 4
FILTER versus CASE: Same Results, Different Readability
Prerequisites
Assume you know basic SELECT, WHERE, aggregate functions such as count and sum, and the meaning of SQL NULL. This chapter uses the orders table from the earlier examples:
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
);Conditional aggregation means applying an aggregate function to only the rows that meet a condition. PostgreSQL offers two common styles:
- Put a
CASEexpression inside the aggregate. - Put a
FILTER (WHERE ...)clause after the aggregate.
Both styles can produce the same result.
The CASE pattern
A CASE expression returns one value when its condition is true and another value when it is false. If you omit ELSE, it returns NULL when the condition is false.
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;For each row, PostgreSQL evaluates the expressions like this:
- A refunded order produces
1for the first expression. - A non-refunded order produces
NULL. - A paid order produces its
amountfor the second expression. - A non-paid order produces
NULL.
count(expression) ignores NULL, so only refunded rows are counted. sum(expression) also ignores NULL, so only paid amounts are added.
The condition and the value being aggregated are combined inside the CASE expression. This works, but the query becomes harder to read when a report contains many conditions.
The FILTER pattern
FILTER separates the condition from the aggregate expression:
SELECT
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders;Here, count(*) receives only refunded rows, and sum(amount) receives only paid rows. The condition is visible next to the aggregate it controls.
The general form is:
aggregate_function(expression) FILTER (WHERE condition)The FILTER clause comes after the aggregate call, including any closing parenthesis:
sum(DISTINCT amount) FILTER (WHERE status = 'paid')Comparing the two forms
| Goal | CASE form | FILTER form |
|---|---|---|
| Count refunded orders | `count(CASE WHEN status = 'refunded' THEN 1 END)` | `count(*) FILTER (WHERE status = 'refunded')` |
| Sum paid amounts | `sum(CASE WHEN status = 'paid' THEN amount END)` | `sum(amount) FILTER (WHERE status = 'paid')` |
| Average paid amount | `avg(CASE WHEN status = 'paid' THEN amount END)` | `avg(amount) FILTER (WHERE status = 'paid')` |
For ordinary conditional aggregates, prefer FILTER in PostgreSQL. It states the intent directly: filter the rows, then aggregate them.
The CASE form remains useful when the expression itself must vary. For example, this query applies different adjustments before summing:
SELECT
sum(
CASE
WHEN status = 'paid' THEN amount
WHEN status = 'refunded' THEN -amount
ELSE 0
END
) AS net_amount
FROM orders;A FILTER clause cannot replace this directly because the aggregate needs a different value for different statuses, rather than simply excluding rows.
Rewriting between the forms
A reliable rewrite follows this pattern:
count(CASE WHEN condition THEN 1 END)becomes:
count(*) FILTER (WHERE condition)Likewise:
sum(CASE WHEN condition THEN expression END)becomes:
sum(expression) FILTER (WHERE condition)The rewrite is not always equivalent if the CASE expression has an ELSE branch or if the aggregate expression can be NULL.
For example:
SELECT
count(*) FILTER (WHERE status = 'paid') AS paid_rows,
count(amount) FILTER (WHERE status = 'paid') AS paid_amounts
FROM orders;The first count includes every paid row. The second count excludes paid rows whose amount is NULL. If amount is declared NOT NULL, these values are equal. Otherwise, they are different.
Choosing a style
Use FILTER when:
- You are using PostgreSQL.
- The condition decides whether a row participates.
- A query contains several conditional aggregates.
- You want the condition to be easy to locate and change.
Use CASE when:
- You need different output values for different conditions.
- You need syntax that works on a database system without
FILTER. - You are building a more complex expression before aggregation.
Both styles can be valid. The important task is to understand whether the condition excludes a row or changes the value contributed by that row.
Exercise
Rewrite sum(CASE WHEN status = 'refunded' THEN amount END) using FILTER. What happens when no refunded row exists?
Show answer
Write sum(amount) FILTER (WHERE status = 'refunded'). It returns NULL when no refunded row exists, unless the result is wrapped in coalesce, such as coalesce(sum(amount) FILTER (WHERE status = 'refunded'), 0).