Sub topic 6
Building a One-Pass Summary Report
This chapter combines several filtered aggregates into one monthly report over the orders table. You compute the totals, the paid revenue and a refund percentage in a single scan, and you check how each column behaves when a month has no matching rows.
What this chapter assumes
You should already know how GROUP BY works and how count, sum and avg treat NULL. You should also know the aggregate(...) FILTER (WHERE ...) syntax from the earlier chapters. Everything here uses the orders 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
);To make the outputs below reproducible, load this small data set. Also set the session time zone, because date_trunc on a timestamptz uses the session zone to decide where a month starts.
SET timezone = 'UTC';
INSERT INTO orders (id, customer_id, status, amount, created_at) VALUES
(1, 10, 'paid', 40.00, '2026-01-05 10:00+00'),
(2, 10, 'refunded', 25.00, '2026-01-20 12:00+00'),
(3, 11, 'paid', 60.00, '2026-01-28 09:30+00'),
(4, 12, 'pending', 15.00, '2026-02-02 08:00+00'),
(5, 11, 'refunded', 30.00, '2026-02-10 14:00+00'),
(6, 12, 'refunded', 20.00, '2026-02-15 16:00+00');January has two paid orders and one refunded order. February has no paid orders at all, which is useful for testing NULL handling later.
The problem: many questions, one table
A product manager asks for a monthly report with these columns:
- total orders
- paid orders
- revenue from paid orders
- the share of orders that were refunded
The naive approach runs one query per column and joins or stitches the results together. Each query scans orders again, and each repeats the same GROUP BY. The result is more SQL to maintain and more chances for the columns to disagree about which months exist.
With FILTER, you group once and give each output column its own condition. PostgreSQL reads each row once and feeds it to every aggregate. Each aggregate decides for itself whether to accept the row.
Step 1: group by month
Start with the grouping and one unfiltered aggregate:
SELECT
date_trunc('month', created_at) AS month,
count(*) AS orders
FROM orders
GROUP BY 1
ORDER BY 1;date_trunc('month', created_at) rounds each timestamp down to the first instant of its month. GROUP BY 1 refers to the first select-list item, so you don't have to repeat the expression. Some teams prefer to write the expression out for clarity. Both forms are valid PostgreSQL.
| month | orders |
|---|---|
| 2026-01-01 00:00:00+00 | 3 |
| 2026-02-01 00:00:00+00 | 3 |
Step 2: add one filtered column per question
Each new column is another aggregate with its own FILTER. Nothing else in the query changes.
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,
round(100.0 * count(*) FILTER (WHERE status = 'refunded') / count(*), 1) AS refund_pct
FROM orders
GROUP BY 1
ORDER BY 1;| month | orders | paid_orders | paid_revenue | refund_pct |
|---|---|---|---|---|
| 2026-01-01 00:00:00+00 | 3 | 2 | 100.00 | 33.3 |
| 2026-02-01 00:00:00+00 | 3 | 0 | NULL | 66.7 |
Three details matter here.
FILTERfollows the closing parenthesis. Writecount(*) FILTER (WHERE ...), notcount(* FILTER ...).- The filters are independent. The
paid_ordersfilter has no effect onordersorrefund_pct. This is the main reason to useFILTERin a report. AWHERE status = 'paid'on the whole query would remove the refunded rows before any aggregate saw them. 100.0forces decimal arithmetic. With the integer100, PostgreSQL would divide twobigintcounts using integer division and truncate the result.100.0makes the whole expressionnumeric, andround(..., 1)keeps one decimal place.
Why the percentage cannot divide by zero
The denominator is count(*), with no filter. In a grouped query, a group exists only because at least one row landed in it, so count(*) is at least 1 in every group. The numerator can be 0, which is fine: 0 divided by 3 is 0.
That guarantee disappears when there is no GROUP BY. A query with aggregates and no grouping always returns exactly one row, even if the table, or the rows left after WHERE, are empty. In that case count(*) is 0 and the division fails with division by zero. Guard it with nullif, which turns a zero denominator into NULL so the whole expression becomes NULL:
SELECT
round(
100.0 * count(*) FILTER (WHERE status = 'refunded') / nullif(count(*), 0),
1
) AS refund_pct
FROM orders
WHERE created_at >= now() - interval '1 day';If no orders arrived in the last day, refund_pct is NULL, which says "undefined". That is more honest than reporting 0%.
Deciding what an empty filter should show
Look at the February row above. No order was paid, so the sum(amount) FILTER (WHERE status = 'paid') aggregate received zero rows. count returns 0 for zero rows, but sum, avg, min and max return NULL. This is why paid_orders shows 0 while paid_revenue shows NULL in the same row.
Whether to convert that NULL depends on the column:
- Sums of money or quantities: usually convert to zero with
coalesce. "No paid orders" means revenue of zero, and a zero is easier for a spreadsheet or chart to handle. - Averages, minimums and maximums: usually leave as NULL. An average of nothing is not 0.00, and showing 0.00 would drag down any later average of the monthly figures.
Here is the report with both choices applied, plus a refunded_orders column and an other_orders column for the statuses you did not name:
SELECT
date_trunc('month', created_at) AS month,
count(*) AS orders,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders,
count(*) FILTER (WHERE status NOT IN ('paid', 'refunded')) AS other_orders,
coalesce(sum(amount) FILTER (WHERE status = 'paid'), 0.00) AS paid_revenue,
round(avg(amount) FILTER (WHERE status = 'paid'), 2) AS avg_paid_amount,
round(100.0 * count(*) FILTER (WHERE status = 'refunded') / count(*), 1) AS refund_pct
FROM orders
GROUP BY 1
ORDER BY 1;| month | orders | paid_orders | refunded_orders | other_orders | paid_revenue | avg_paid_amount | refund_pct |
|---|---|---|---|---|---|---|---|
| 2026-01-01 00:00:00+00 | 3 | 2 | 1 | 0 | 100.00 | 50.00 | 33.3 |
| 2026-02-01 00:00:00+00 | 3 | 0 | 2 | 1 | 0.00 | NULL | 66.7 |
The other_orders column is a reconciliation check. If paid_orders + refunded_orders + other_orders does not equal orders for some month, one of your conditions is wrong. Because status is declared NOT NULL, NOT IN is safe here. On a nullable column, a NULL status would make status NOT IN (...) evaluate to NULL, and FILTER would skip the row.
Filters can overlap
Nothing forces the conditions to be mutually exclusive. A row can pass several filters and contribute to several columns. For example, you may want to know how many paid orders were large:
SELECT
date_trunc('month', created_at) AS month,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
count(*) FILTER (WHERE status = 'paid' AND amount >= 50) AS large_paid_orders
FROM orders
GROUP BY 1
ORDER BY 1;The row for order 3 (paid, 60.00) is counted in both columns. That is correct, since the columns answer different questions. The consequence is that you can't add the columns together and expect the total, as you can with disjoint conditions like the three statuses above.
The same report with CASE
Before FILTER existed, you would write each column with a CASE expression. This is still the form you need on databases without FILTER, and it produces identical results:
SELECT
date_trunc('month', created_at) AS month,
count(*) AS orders,
count(CASE WHEN status = 'paid' THEN 1 END) AS paid_orders,
sum(CASE WHEN status = 'paid' THEN amount END) AS paid_revenue
FROM orders
GROUP BY 1
ORDER BY 1;The CASE returns NULL when the condition fails, because there is no ELSE, and count(expr) and sum skip NULLs. For reports with many columns, the FILTER version is easier to scan because the aggregated expression and the condition are separate. The empty-group behavior is the same in both forms.
Common mistakes in report queries
| Mistake | What happens | Fix |
|---|---|---|
| Adding `WHERE status = 'paid'` to the whole query | Every column, including the totals, sees only paid rows | Move the condition into the `FILTER` of the column that needs it |
| `count(amount) FILTER (...)` where `count(*)` was meant | Rows with a NULL `amount` are skipped; here `amount` is `NOT NULL`, so the result matches, but the habit fails on nullable columns | Use `count(*)` to count rows, and `count(col)` only when you want to skip NULLs |
| Dividing two counts with integer literals | The percentage is truncated, for example 33 instead of 33.3 | Multiply by `100.0` |
| Wrapping `avg` in `coalesce(..., 0)` | Empty months show an average of 0 and distort later calculations | Leave it NULL, or label it in the presentation layer |
| Relying on `GROUP BY 1` after reordering the select list | You silently group by a different column | Keep the grouping expression first, or write it out |
Reading the result before you trust it
For a report like this, check three things:
- Compare the totals against a plain
SELECT count(*) FROM ordersand a plainsum(amount). They should match the sum of the monthly rows. - Check that
paid_orders + refunded_orders + other_orders = ordersin every row. - Look at the months with no matches. A NULL, 0 or 0.00 in those cells confirms that your empty-set handling does what you intended.
Exercise
Extend the monthly report with a column pending_revenue that shows the total amount of pending orders, as 0.00 when a month has none. Then say what value pending_revenue has for January and February in the sample data, and why the January value is not NULL even though January has no pending orders.
Show answer
Add coalesce(sum(amount) FILTER (WHERE status = 'pending'), 0.00) AS pending_revenue to the select list. January has no pending orders, so the filtered sum receives zero rows and returns NULL, and coalesce replaces it with 0.00. February has one pending order of 15.00, so pending_revenue is 15.00. The January value is not NULL in the output only because coalesce converts the NULL produced by sum into 0.00. Without coalesce it would be NULL.
Exercise
A colleague writes round(100 * count(*) FILTER (WHERE status = 'refunded') / count(*), 1) and gets 33.0 for January instead of 33.3. What went wrong, and what is the smallest change that fixes it?
Show answer
The literal 100 is an integer, so 100 * 1 / 3 is evaluated as integer division on bigint values and truncated to 33 before round runs. Changing 100 to 100.0 makes the expression numeric, and the result becomes 33.3.