Sub topic 3
Meet `FILTER (WHERE ...)`
Assume you know basic SELECT, WHERE, ORDER BY, and aggregate functions such as count, sum, and avg. You should also know that SQL NULL means “missing or unknown,” not zero.
PostgreSQL’s FILTER clause lets an aggregate function use only the rows that match a condition. The query can still read the complete input set, while each aggregate receives its own subset.
Consider 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
);Without FILTER, a query can count every order:
SELECT count(*) AS total_orders
FROM orders;To count only refunded orders, place FILTER (WHERE ...) after the aggregate call:
SELECT
count(*) AS total_orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders
FROM orders;The first count receives every row. The second count receives only rows whose status is refunded. Both results appear in one row.
How the clause works
The general form is:
aggregate_function(expression)
FILTER (WHERE condition)For example, this calculates the total value of paid orders:
SELECT
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders;The expression being aggregated is amount. The filter decides which rows contribute that amount.
You can use different conditions on different aggregates:
SELECT
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders,
avg(amount) FILTER (WHERE status = 'pending') AS average_pending_amount
FROM orders;This is useful when a report needs several measures from the same table. Each aggregate has an independent filter.
The query-level WHERE clause has a different scope:
SELECT
count(*) AS recent_orders,
count(*) FILTER (WHERE status = 'refunded') AS recent_refunds
FROM orders
WHERE created_at >= now() - interval '30 days';First, the query-level WHERE removes orders older than 30 days. Then each aggregate applies its own FILTER condition to the remaining rows. In this example, both counts describe recent orders.
Using `FILTER` with grouped results
When you add GROUP BY, PostgreSQL creates one result row per group. Each filtered aggregate then works inside its group.
SELECT
customer_id,
count(*) AS total_orders,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders
FROM orders
GROUP BY customer_id
ORDER BY customer_id;For each customer, total_orders counts all that customer’s orders. The other columns count only orders with the specified status.
The condition can contain several predicates:
SELECT
count(*) FILTER (
WHERE status = 'paid'
AND amount >= 100
) AS large_paid_orders
FROM orders;The filter condition follows normal SQL rules. You can use comparisons, AND, OR, IN, date expressions, and other expressions that are valid in a WHERE clause.
FILTER also works with aggregates that process an expression rather than *:
SELECT
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue,
max(amount) FILTER (WHERE status = 'refunded') AS largest_refund
FROM orders;The aggregate receives no rows that fail its filter. This detail matters for sum, avg, and other functions whose result can become NULL when no matching row exists.
Exercise
Write a query that returns the total number of orders and the total amount of orders with status paid.
Show answer
SELECT count(*) AS totalorders, sum(amount) FILTER (WHERE status = 'paid') AS paidrevenue FROM orders;