Sub topic 3
Meet FILTER (WHERE ...)
This chapter introduces the FILTER clause: its syntax, where it sits in query evaluation, and how to read and write it. It assumes you can write SELECT, WHERE and ORDER BY. It also assumes you know count, sum and avg with GROUP BY, and that you know NULL means "unknown" in SQL. FILTER has been available since PostgreSQL 9.4.
The problem FILTER solves
An aggregate function normally sees every row in its group. Suppose you want the number of all orders and the number of refunded orders. A WHERE status = 'refunded' clause cuts the rows for the whole query, so the total count is lost. Without FILTER, you would run two queries, or you would use CASE inside the aggregate.
FILTER attaches a condition to a single aggregate call. Each aggregate in the SELECT list can then see a different subset of the same rows.
Sample data
All examples use the orders table from the plan. Create it and load a few rows so you can check the results.
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-11-01 09:00+00'),
(2, 10, 'refunded', 25.00, '2026-11-02 10:00+00'),
(3, 11, 'paid', 60.00, '2026-11-03 11:00+00'),
(4, 12, 'pending', 15.00, '2026-11-04 12:00+00'),
(5, 11, 'paid', 100.00, '2026-11-05 13:00+00'),
(6, 12, 'refunded', 30.00, '2026-11-06 14:00+00');The table has 6 orders: 3 paid (total 200.00), 2 refunded and 1 pending.
The syntax
The general form of an aggregate call with a filter is:
aggregate_name ( [ DISTINCT ] expression [, ...] [ ORDER BY ... ] )
FILTER ( WHERE condition )Three points follow from this form:
FILTERcomes after the closing parenthesis of the aggregate call. It is not an argument.- The condition is a boolean expression, written like the one in a
WHEREclause. It is evaluated once per input row. - A row reaches the aggregate only if the condition is true. Rows where the condition is false or
NULLare skipped for that aggregate only.
A first query
SELECT
count(*) AS total_orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders
FROM orders;Result:
total_orders | refunded_orders
--------------+-----------------
6 | 2The first count(*) has no filter, so it counts all 6 rows. The second counts only rows where status = 'refunded'. Both aggregates read the same scan of the table.
The same pattern works for sums. The condition is separate from the expression being summed, which makes each part easy to read:
SELECT
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders;Result:
refunded_orders | paid_revenue
-----------------+--------------
2 | 200.00The expression inside the parentheses (amount) is what gets summed. The filter decides which rows contribute it.
Where FILTER sits in query evaluation
A query with GROUP BY runs in this order:
FROMproduces the rows.WHEREremoves rows for the whole query.GROUP BYforms groups from the surviving rows.- For each group, each aggregate applies its own
FILTER, if it has one, and consumes the rows that pass. HAVINGfilters the finished groups.
Because WHERE runs first, it limits what every filter can see. This query counts only orders from 3 November onward, and then separates refunded orders within them:
SELECT
count(*) AS orders_since_nov_3,
count(*) FILTER (WHERE status = 'refunded') AS refunded_since_nov_3
FROM orders
WHERE created_at >= '2026-11-03 00:00+00';This returns 4 and 1. Orders 1 and 2 are removed by WHERE before any aggregate runs. Order 6 is the only refunded order in the remaining four rows (orders 3 to 6) that passes the filter... but order 2 was refunded earlier and is gone, so the refunded count is 1.
The filter can only narrow what WHERE already let through. It cannot bring back rows that WHERE removed.
FILTER with GROUP BY
FILTER is most useful when you group. Each group evaluates every filter against its own rows:
SELECT
customer_id,
count(*) AS orders,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders
GROUP BY customer_id
ORDER BY customer_id;Result:
customer_id | orders | paid_orders | paid_revenue
-------------+--------+-------------+--------------
10 | 2 | 1 | 40.00
11 | 2 | 2 | 160.00
12 | 2 | 0 |Customer 12 has two orders, and neither is paid. The count returns 0, but sum returns NULL, which psql shows as an empty cell. The next chapters explain this difference and how to handle it. For now, note that FILTER does not remove the group. Customer 12 still appears because the group was formed before any filter ran.
What the condition can contain
The condition accepts anything you would write in a WHERE clause that evaluates per row:
- Comparisons,
IN,BETWEEN,LIKE, andIS NULLorIS NOT NULL. - Combinations with
AND,ORandNOT. - Function calls and expressions on the row's columns, such as
date_truncorextract.
SELECT
count(*) FILTER (WHERE status IN ('paid', 'refunded')
AND amount >= 30) AS settled_30_plus,
avg(amount) FILTER (WHERE status <> 'pending') AS avg_non_pending
FROM orders;Orders 1, 2 (25.00 fails), 3, 5 and 6 are settled; of those with amount >= 30: orders 1, 3, 5 and 6, so settled_30_plus is 4. The average of non-pending amounts is (40 + 25 + 60 + 100 + 30) / 5 = 51.0000000000000000.
Each aggregate has its own condition, and they do not need to be related. They can overlap, as in the example above, where one order can satisfy several filters.
A condition that evaluates to NULL excludes the row, the same as WHERE. If a column can be NULL, FILTER (WHERE col <> 'x') skips rows where col is NULL. Add OR col IS NULL if you want them.
Choosing between count(*) and count(expression)
With FILTER, count(*) is the natural choice for "how many rows match". The filter already decided which rows count, so you do not need an expression that might be NULL. Use count(column) FILTER (WHERE ...) only when you also want to skip rows where column is NULL:
SELECT
count(*) FILTER (WHERE status = 'paid') AS paid_rows,
count(amount) FILTER (WHERE status = 'paid') AS paid_rows_with_amount
FROM orders;Here amount is NOT NULL, so both columns give 3. On a nullable column they could differ.
Limits you will meet right away
FILTER is only valid on aggregate functions. Using it on an ordinary function fails at parse time:
SELECT round(amount) FILTER (WHERE status = 'paid') FROM orders;
-- ERROR: FILTER specified, but round is not an aggregate functionThe condition also cannot contain an aggregate or a window function. FILTER (WHERE amount > avg(amount)) is rejected, because the filter is evaluated row by row, before any aggregate has a result. If you need a comparison with a group-level value, compute it in a subquery or a CTE first.
Later chapters cover the other places FILTER can appear, and the other limits.
A quick mental model
Read agg(x) FILTER (WHERE p) as "aggregate x over only the rows where p is true". The aggregate never sees other rows, so they affect neither the result nor the NULL-skipping logic. This also explains why count(*) FILTER (WHERE p) counts matching rows and returns 0 when none match, since a count over zero rows is zero.
Exercise
Using the orders table, write one query that returns, per customer_id, the number of orders with status 'pending' and the largest amount among orders with status 'refunded'. Which customers will show NULL for the second column, and why? Use the sample data.
Show answer
SELECT customerid, count(*) FILTER (WHERE status = 'pending') AS pendingorders, max(amount) FILTER (WHERE status = 'refunded') AS largestrefund FROM orders GROUP BY customerid ORDER BY customerid; Customer 11 shows NULL for largestrefund because none of its orders is refunded, so max receives no rows and returns NULL. Customer 10 has largestrefund 25.00 and 0 pending orders. Customer 12 has 1 pending order and largestrefund 30.00.
Exercise
A colleague writes: SELECT count(*) FILTER (WHERE amount > avg(amount)) FROM orders; The query fails. Why does it fail, and what is one way to fix it?
Show answer
The FILTER condition is evaluated per input row, before any aggregate result exists, so it cannot contain an aggregate such as avg. One fix is to compute the average in a subquery or CTE and compare against it: WITH a AS (SELECT avg(amount) AS avgamount FROM orders) SELECT count(*) FILTER (WHERE o.amount > a.avgamount) FROM orders o CROSS JOIN a;