Sub topic 11
Performance: one scan instead of many, and reading EXPLAIN
This chapter assumes you can run EXPLAIN and EXPLAIN ANALYZE at a basic level, and that you know the orders table and the FILTER (WHERE ...) syntax from earlier chapters. Here you will measure what a filtered aggregate costs, compare it with several separate queries, and read the plan to confirm the table is scanned only once.
Why one pass matters
A summary report often needs several numbers. A common first attempt is one query per number, or one scalar subquery per number:
SELECT
(SELECT count(*) FROM orders) AS total_orders,
(SELECT count(*) FROM orders WHERE status = 'refunded') AS refunded_orders,
(SELECT sum(amount) FROM orders WHERE status = 'paid') AS paid_revenue;This is correct, but PostgreSQL plans each subquery separately. With no helpful index, that means three sequential scans of orders. The table is read from disk (or from the buffer cache) three times, and every row is visited three times.
The FILTER version computes the same three numbers in one scan:
SELECT
count(*) AS total_orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders;Each row is read once. For every row, the executor updates each aggregate's running state, and a FILTER condition decides whether that aggregate sees the row. The extra work per row is a few cheap comparisons. The saved work is two full passes over the table.
Setting up test data
To see the difference yourself, load enough rows that a scan takes measurable time. This script fills the orders table with one million rows. About 10% are refunded, 20% pending, and 70% paid.
INSERT INTO orders (id, customer_id, status, amount, created_at)
SELECT
g,
(g % 5000) + 1,
CASE WHEN g % 10 = 0 THEN 'refunded'
WHEN g % 10 < 3 THEN 'pending'
ELSE 'paid' END,
round((random() * 200)::numeric + 1, 2),
now() - (g % 365) * interval '1 day'
FROM generate_series(1, 1000000) AS g;
ANALYZE orders;ANALYZE refreshes the planner's statistics so the row estimates in EXPLAIN are realistic.
Reading the plan
Run EXPLAIN on the FILTER query:
EXPLAIN (ANALYZE, BUFFERS)
SELECT
count(*) AS total_orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders;The output looks like this. It is abridged and representative, and your costs, timings and buffer counts will differ.
Aggregate (cost=26370.00..26370.01 rows=1 width=48) (actual time=212.4..212.4 rows=1 loops=1)
Buffers: shared hit=8334
-> Seq Scan on orders (cost=0.00..16370.00 rows=1000000 width=14) (actual time=0.02..71.3 rows=1000000 loops=1)
Buffers: shared hit=8334
Planning Time: 0.1 ms
Execution Time: 212.5 msLook at three things:
- One scan node. There is a single
Seq Scan on ordersunder theAggregatenode. That confirms the one-pass behavior. Buffers. The number of pages touched is the table size once. The three-subquery version reports roughly three times that.- The FILTER conditions are not visible by default. Plain
EXPLAINhides the aggregate expressions. AddVERBOSEto see them:
EXPLAIN (VERBOSE, COSTS OFF)
SELECT
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders;Aggregate
Output: count(*) FILTER (WHERE (orders.status = 'refunded'::text)), sum(orders.amount) FILTER (WHERE (orders.status = 'paid'::text))
-> Seq Scan on orders
Output: id, customer_id, status, amount, created_atThe Output line shows each aggregate with its own condition. The scan has no Filter: line. The conditions belong to the aggregates, not to the scan, so every row is returned by the scan and tested inside the aggregate step.
Now compare the plan for the three-subquery version. You will see an InitPlan for each subquery, each with its own Aggregate and Seq Scan on orders. Three scans of the same table is the signal to rewrite.
FILTER versus CASE: cost
Rewriting FILTER as CASE does not change the scan count. Both forms are evaluated inside the aggregate step during a single pass:
SELECT
count(*) AS total_orders,
count(CASE WHEN status = 'refunded' THEN 1 END) AS refunded_orders,
sum(CASE WHEN status = 'paid' THEN amount END) AS paid_revenue
FROM orders;Run EXPLAIN (ANALYZE, BUFFERS) on both forms and the plans have the same structure. Any timing difference is small and mostly noise. FILTER is evaluated by the aggregate machinery itself, so the executor does not build an intermediate CASE value for each row. That can be marginally cheaper, but you should choose between them for readability, not speed. The earlier chapter on FILTER versus CASE covers that choice.
Push shared conditions into WHERE
FILTER does not reduce the rows the scan reads. If every number in the report concerns the same subset, a WHERE clause is better, because the scan can skip rows and can use an index.
SELECT
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders
FROM orders
WHERE created_at >= date '2026-01-01'
AND created_at < date '2026-02-01';The date range applies to all three aggregates, so it belongs in WHERE. An index on created_at can then limit the scan to one month of rows.
You can go one step further when no aggregate needs rows outside a set of statuses. Here every aggregate looks only at paid or refunded rows, so a WHERE status IN (...) is safe:
SELECT
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders
FROM orders
WHERE status IN ('paid', 'refunded');When separate queries can win
One scan is not always the fastest plan. Suppose refunds are rare, say 0.1% of rows, and a partial index exists:
CREATE INDEX orders_refunded_idx
ON orders (customer_id)
WHERE status = 'refunded';A query that counts only refunded orders can use this small index and avoid reading most of the table:
EXPLAIN
SELECT count(*) FROM orders WHERE status = 'refunded';The plan can choose an Index Only Scan or Bitmap Heap Scan on orders_refunded_idx. A combined FILTER query that also needs count(*) over every row has no choice but to read the whole table, so the index does not help it. If one of the numbers is highly selective and the others are cheap or cached, running two queries can be faster than one broad scan. Decide with measurements:
| Situation | Better approach |
|---|---|
| Several aggregates over most or all rows of the same table | One query with FILTER |
| All aggregates share one condition | Move that condition into WHERE |
| One aggregate is highly selective and backed by an index, others need the whole table | Test separate queries against the combined one |
| Aggregates come from different tables | Separate subqueries or a join, FILTER does not help here |
Also be careful when a report joins to another table before aggregating. A join can multiply rows, and then every filtered count is inflated. Aggregate first in a subquery or CTE, then join the result.
Costs that grow with the aggregate list
The cost of a FILTER query is not constant as you add columns:
- Each aggregate adds CPU per row. Twenty filtered aggregates over a million rows is twenty million condition checks. This is usually still much cheaper than twenty scans, but it is not free. If
EXPLAIN ANALYZEshows theAggregatenode taking far longer than theSeq Scanbeneath it, the aggregate work is the bottleneck. - Expensive filter expressions are evaluated for every row. A condition such as
WHERE lower(status) LIKE 'ref%'or a call to a slow function runs once per aggregate per row. If several aggregates share the same expensive test, compute it once in a subquery and filter on the result. - Grouped queries add hashing or sorting. With
GROUP BY, the plan usesHashAggregateorGroupAggregatewith aSort. A high number of groups can make memory use, not the scan, the main cost. InEXPLAIN ANALYZE, look forBatchesgreater than 1 orDisk:in a HashAggregate node, which means the hash table spilled to disk. Raisingwork_memfor that session can help. - DISTINCT and ORDER BY inside an aggregate add a sort per aggregate. These aggregates do not support PostgreSQL's partial aggregation, so a query that uses them cannot use parallel aggregation for that step. Check the plan for
GatherandPartial Aggregatenodes, and expect a plain single-processAggregatewhenstring_agg(DISTINCT ...)orarray_agg(... ORDER BY ...)is present.
For large plain aggregates, PostgreSQL can run a parallel plan. FILTER works with it, and the plan then shows Finalize Aggregate, Gather and Partial Aggregate above a Parallel Seq Scan. The FILTER conditions are evaluated in the partial step in each worker.
A repeatable measuring routine
- Write the one-pass query and, for comparison, the multi-subquery version.
- Run
ANALYZEon the table so estimates are current. - Run
EXPLAIN (ANALYZE, BUFFERS)on each, twice, and use the second run to reduce cold-cache effects. - Count the
Seq Scanor index scan nodes onorders, and compareBuffers. - Use
EXPLAIN (VERBOSE)once to confirm each aggregate carries the filter you intended. - Check the row estimate against the actual rows on the scan node. A large mismatch means stale statistics, not a FILTER problem.
Exercise
A report runs three scalar subqueries over orders: count(*), count(*) where status = 'refunded', and sum(amount) where status = 'paid'. EXPLAIN shows three Seq Scan nodes on orders. You rewrite it as one FILTER query. What should the new plan show, and why is moving WHERE status IN ('paid', 'refunded') into the rewritten query a mistake here?
Show answer
The new plan should show one Aggregate node over a single Seq Scan on orders, and Buffers should drop to about a third. EXPLAIN (VERBOSE) shows each aggregate with its own FILTER condition. Adding WHERE status IN ('paid', 'refunded') is a mistake because the report contains an unfiltered count(*) for all orders. The WHERE clause would remove pending orders from that count and give a wrong total. A shared condition belongs in WHERE only when every aggregate in the query can accept it.
Exercise
A query with ten FILTER aggregates scans a million rows once, yet EXPLAIN ANALYZE shows the Aggregate node taking 900 ms while the Seq Scan below it finishes in 70 ms. What does this tell you, and what are two things you could try?
Show answer
The time is going into evaluating the aggregates per row, not into reading the table, so removing scans will not help. Two options: simplify or precompute an expensive condition that several aggregates share (for example, compute a boolean in a subquery and filter on that column), or reduce the number of rows reaching the aggregate with a WHERE clause for any condition common to all aggregates. If the query uses DISTINCT or ORDER BY inside aggregates, also check whether those sorts are the cost.