Sub topic 11
Performance: one scan instead of many, and reading EXPLAIN
Assume you know SELECT, WHERE, GROUP BY, aggregate functions, and basic NULL behavior. This chapter focuses on PostgreSQL query plans rather than on the basic syntax of FILTER.
A filtered aggregate lets one query calculate several conditional results while PostgreSQL reads the input rows once for that query. For example:
SELECT
date_trunc('month', created_at) AS month,
count(*) AS orders,
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
GROUP BY 1
ORDER BY 1;The scan supplies each row to the grouping operation. For each row, PostgreSQL evaluates the filter for each aggregate. A row can contribute to several aggregates, one aggregate, or none of them.
Compare one query with many queries
Running separate queries for each metric repeats work:
SELECT count(*) FROM orders;
SELECT count(*) FROM orders WHERE status = 'paid';
SELECT sum(amount) FROM orders WHERE status = 'paid';
SELECT count(*) FROM orders WHERE status = 'refunded';Each statement may scan orders, apply predicates, and perform its own aggregation. A single query with filtered aggregates can usually share the scan and grouping work.
This does not mean that FILTER always makes a query fast. The database still evaluates every filter for every input row. If the table is large, the scan and grouping may remain expensive. The benefit is that several related results can be produced without repeating the complete query pipeline.
Read the plan with EXPLAIN
Use EXPLAIN to see the plan PostgreSQL intends to use:
EXPLAIN
SELECT
date_trunc('month', created_at) AS month,
count(*) AS orders,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders
GROUP BY 1
ORDER BY 1;EXPLAIN ANALYZE runs the query and includes actual timing and row counts:
EXPLAIN (ANALYZE, BUFFERS)
SELECT
date_trunc('month', created_at) AS month,
count(*) AS orders,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders
WHERE created_at >= timestamptz '2026-01-01 00:00:00+00'
GROUP BY 1
ORDER BY 1;Look for these parts:
| Plan detail | What it tells you |
|---|---|
| `Seq Scan` or `Index Scan` | How PostgreSQL reads the input rows |
| `Filter` | Which rows are removed before later operations |
| `GroupAggregate` or `HashAggregate` | How groups and aggregate states are calculated |
| `actual time` and `rows` | What happened during execution |
| `Buffers` | How many shared memory or disk pages were accessed |
A condition in the query's WHERE clause can reduce the rows entering the aggregation. A condition inside FILTER usually cannot remove rows from the scan because other aggregates may need those rows.
For example, this query can use an index or partition pruning opportunity based on created_at:
SELECT
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders
FROM orders
WHERE created_at >= now() - interval '30 days';The date condition removes old rows before the aggregates run. The two status conditions remain separate because each aggregate needs a different subset.
Check estimates and real measurements
In an EXPLAIN ANALYZE plan, compare estimated rows with actual rows. A large difference can lead PostgreSQL to choose a poor join, scan, or aggregation strategy. ANALYZE orders; updates table statistics, but it does not guarantee a better plan.
Test realistic data and parameters. A query that is fast on a table with 1,000 rows may behave differently with 100 million rows. Compare equivalent FILTER and CASE forms only after measuring them on your workload. Their results are often the same, but execution details can differ.
Exercise
Why might a query with several FILTER aggregates be faster than several separate aggregate queries?
Show answer
One query can share the scan, filtering of common rows, grouping, and result construction instead of repeating that work for every metric.