Sub topic 1
Conditional Aggregation in PostgreSQL with FILTER
Prerequisites
This chapter assumes you can write basic SELECT, WHERE and ORDER BY clauses. You should know the aggregate functions count, sum and avg, and understand how NULL behaves in SQL.
Refresher: aggregates and GROUP BY
An aggregate function collapses many rows into one value. GROUP BY splits rows into groups, and the aggregate runs once per group. The examples use this table:
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
);SELECT customer_id, count(*) AS orders, sum(amount) AS total
FROM orders
GROUP BY customer_id;Each output row describes one customer. Every column that is not inside an aggregate must appear in GROUP BY.
The classic approach: CASE inside an aggregate
Suppose you want the number of refunded orders and the revenue from paid orders in one result. A CASE expression returns a value for matching rows and NULL for the rest. Aggregates skip NULL values, so the CASE expression effectively filters the input.
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;This pattern works in any SQL database. However, the condition and the value are mixed into one expression, which makes longer queries harder to scan.
Meet FILTER (WHERE ...)
PostgreSQL offers FILTER, a clause written after an aggregate call. FILTER lets the aggregate see only the rows that pass its condition.
SELECT
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders;FILTER versus CASE: same results, different readability
The two queries above return the same numbers. FILTER places each condition next to the aggregate it controls, so each column reads as one idea. CASE still matters for code that must run on databases without FILTER support.
Exercise
Rewrite this query using FILTER: SELECT sum(CASE WHEN status = 'paid' THEN amount END) AS paid_revenue FROM orders;
Show answer
SELECT sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue FROM orders;