Sub topic 10
Combining FILTER with GROUPING SETS and ROLLUP
A report often needs detail rows, subtotals and a grand total, each with several conditional measures. This chapter shows how to get all of that from one query by putting FILTER aggregates on top of GROUPING SETS, ROLLUP and CUBE.
This chapter assumes you know the FILTER (WHERE ...) syntax from earlier chapters, GROUP BY with aggregates, and how count and sum treat NULL. It uses the orders table from the start of the tutorial.
What the combination does
GROUPING SETS tells PostgreSQL to group the same input rows in several ways in one pass. FILTER decides which rows each aggregate receives. The two features work independently:
- PostgreSQL forms the groups for each grouping set.
- Inside each group, every aggregate applies its own
FILTERcondition to the group's rows. - The result is one output row per group, and the rows from all sets are concatenated.
A filtered aggregate is therefore computed once for every grouping set. Its condition may use any column of the input row, including columns that the current set does not group by.
GROUPING SETS with filtered aggregates
Here is a query with three grouping sets: per customer, per status, and everything together (the empty set ()).
SELECT
customer_id,
status,
count(*) AS orders,
count(*) FILTER (WHERE amount >= 100) AS large_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders
GROUP BY GROUPING SETS ((customer_id), (status), ())
ORDER BY customer_id, status;The output contains three kinds of rows:
- Rows from
(customer_id)have a customer and a NULLstatus, becausestatusis not part of that grouping. - Rows from
(status)have a status and a NULLcustomer_id. - One row from
()has NULL in both columns and covers the whole table.
Look at paid_revenue in each kind of row. In the per-customer rows, the filter on status still works, even though status is not a grouping column. Inside an aggregate, status refers to each individual input row, so the sum covers only that customer's paid orders. In the (status) rows, the filter on status matches only the paid group. The refunded and pending groups contain no paid rows, so their paid_revenue is NULL.
That second case is a reminder that a condition on a grouping column is redundant in some sets and decisive in others. Choose the condition because of what the column should measure, not because of how a particular set is grouped.
ROLLUP for subtotals
ROLLUP (a, b) is shorthand for the sets (a, b), (a) and (). It produces detail rows, then subtotals, then a grand total. Listing the columns from the coarsest to the finest level gives the hierarchy you usually want, such as year then month.
To avoid repeating date_trunc expressions, compute the time buckets in a CTE first.
WITH o AS (
SELECT
date_trunc('year', created_at) AS year,
date_trunc('month', created_at) AS month,
status,
amount
FROM orders
)
SELECT
year,
month,
count(*) AS orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders,
coalesce(sum(amount) FILTER (WHERE status = 'paid'), 0) AS paid_revenue
FROM o
GROUP BY ROLLUP (year, month)
ORDER BY year, month;ORDER BY year, month puts NULLs last by default. Each year's monthly rows are followed by that year's subtotal (month is NULL), and the grand total comes at the very end.
Every row has the same columns and uses the same measure definitions. The subtotal for refunded orders is the number of refunded orders in the year, not the sum of some other number. This consistency is the main reason to use ROLLUP instead of stitching the report together with UNION ALL.
Telling real NULLs from rollup NULLs
A rolled-up column is shown as NULL. If the grouping column can also contain real NULLs, a NULL in the output is ambiguous. In the sample table, customer_id and status are NOT NULL, so the problem does not arise there. It does arise with nullable columns such as an optional region or a nullable date.
The grouping() function resolves the ambiguity. It takes one or more grouping expressions and returns a bitmask: each bit is 1 if that expression was not part of the current row's grouping set. The leftmost argument is the highest bit.
| Row type | year | month | `grouping(year, month)` |
|---|---|---|---|
| Month detail | a value | a value | 0 |
| Year subtotal | a value | NULL | 1 |
| Grand total | NULL | NULL | 3 |
Use it to build a readable label column:
WITH o AS (
SELECT
date_trunc('year', created_at) AS year,
date_trunc('month', created_at) AS month,
status,
amount
FROM orders
)
SELECT
CASE grouping(year, month)
WHEN 0 THEN 'month'
WHEN 1 THEN 'year'
ELSE 'total'
END AS level,
year,
month,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
coalesce(sum(amount) FILTER (WHERE status = 'paid'), 0) AS paid_revenue
FROM o
GROUP BY ROLLUP (year, month)
ORDER BY year, month;grouping() can appear only in the select list, HAVING and ORDER BY of a grouped query. It cannot go inside a FILTER clause, because FILTER runs per input row and the grouping level belongs to the group. You can still use it in HAVING to pick which levels to keep:
WITH o AS (
SELECT
date_trunc('year', created_at) AS year,
date_trunc('month', created_at) AS month,
status,
amount
FROM orders
)
SELECT
year,
month,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders
FROM o
GROUP BY ROLLUP (year, month)
HAVING grouping(month) = 0 OR grouping(year) = 1
ORDER BY year, month;This returns the monthly detail rows and the grand total, and drops the yearly subtotals.
CUBE and several independent dimensions
CUBE (a, b) produces every combination: (a, b), (a), (b) and (). It suits a cross-tab style report where neither dimension is a parent of the other. ROLLUP suits a hierarchy.
WITH o AS (
SELECT
date_trunc('month', created_at) AS month,
status,
amount
FROM orders
)
SELECT
month,
status,
count(*) AS orders,
count(*) FILTER (WHERE amount >= 100) AS large_orders
FROM o
GROUP BY CUBE (month, status)
ORDER BY month, status;The number of sets grows as 2 to the power of the number of columns, so CUBE over five columns gives 32 sets. Check that you really need all of them. If you need only a few combinations, list them explicitly with GROUPING SETS.
Edge cases to know
Empty input still returns a grand total
A plain SELECT count(*), sum(amount) FROM orders returns one row even when the table is empty: count is 0 and sum is NULL. The empty grouping set () behaves the same way. A query with GROUPING SETS (..., ()) or a ROLLUP returns a grand-total row even if there is nothing to group, and its filtered aggregates follow the usual rule: count gives 0, sum gives NULL. Wrap sum in coalesce when the report needs 0.
Groups where the filter never matches
In a group where no row passes the filter, count(*) FILTER (...) returns 0 and sum(...) FILTER (...) returns NULL. The row still exists, because the group exists. Only the aggregate's input is empty. This is different from putting the condition in WHERE, which removes the rows (and sometimes entire groups) before grouping.
WHERE applies to every set
A WHERE clause is applied before any grouping set is formed. If you write WHERE status = 'paid' the subtotals and the grand total also count only paid orders. Use FILTER when some columns of the report need a narrower population than others, and use WHERE only for restrictions that apply to the entire report, such as a date range.
Duplicate sets produce duplicate rows
GROUP BY ROLLUP (a), ROLLUP (a) and GROUPING SETS ((a), (a)) can produce the same set more than once. In PostgreSQL, listing the same set twice in one GROUP BY yields duplicate output rows unless you write GROUP BY DISTINCT. Keep your set lists free of overlap.
Performance and reading the plan
The usual reason to combine these features is to scan the table once. The alternative is a UNION ALL of several GROUP BY queries, each of which scans the table again. To compare, run:
EXPLAIN (ANALYZE, VERBOSE)
SELECT
customer_id,
status,
count(*) FILTER (WHERE amount >= 100) AS large_orders
FROM orders
GROUP BY GROUPING SETS ((customer_id), (status), ());In the output, look for:
- A single scan node on
orders, instead of one per grouping set. - An aggregate node that lists several
Group Keylines, one per set. Depending on the sets and available memory, PostgreSQL may use sorting, hashing, or a mix of both (shown asMixedAggregate). - The
FILTER (WHERE ...)conditions in the aggregate's output list, which shows that each filter is evaluated while rows are fed to the aggregate.
Some costs stay the same. Every filtered aggregate is evaluated in every set, so a report with 4 sets and 6 filtered measures does 24 aggregate computations per qualifying row. For tables that are not huge, this is cheap compared with reading the table again. If a set requires a sort on a different key than the others, PostgreSQL adds a sort step. Sets that share a prefix, such as those from ROLLUP, can reuse one sort.
Common mistakes
- Using NULL to detect subtotal rows. Use
grouping(). See the section above. - Forgetting
coalesceon the filtered sum. A group with no matching rows shows NULL, which may appear as a blank in the report. - Putting a report-wide condition in
FILTERon every column. Move it toWHERE. It is clearer and lets PostgreSQL discard rows early, possibly through an index. - Expecting subtotals to be sums of the displayed rows. Subtotals are computed from the input rows. With
count(DISTINCT ...)or averages, a subtotal is not the sum of its children. - Ordering rows without thinking about NULLs. The default
ASCorder puts NULLs last, which suits subtotal rows. If you sort descending, subtotals come first unless you addNULLS LAST.
Exercise
Write a query on the orders table that returns, for each customer and for the whole table together, the number of orders and the number of refunded orders. Use GROUPING SETS and FILTER. Then say how you would label the grand-total row without checking for NULL in customer_id.
Show answer
SELECT customerid, count() AS orders, count() FILTER (WHERE status = 'refunded') AS refundedorders, grouping(customerid) AS istotal FROM orders GROUP BY GROUPING SETS ((customerid), ()) ORDER BY customerid; The grand-total row is the one where grouping(customerid) returns 1, so a CASE on grouping(customerid) can print 'All customers' for it. Testing customer_id IS NULL would also work in this table because the column is NOT NULL, but grouping() stays correct if the column ever allows NULLs.
Exercise
A ROLLUP (year, month) report shows NULL in the paid_revenue column for a month in which every order was refunded. What causes this, and what is the fix?
Show answer
The month's group exists, but no row passes FILTER (WHERE status = 'paid'), so sum receives no input and returns NULL. Wrap the aggregate in coalesce, for example coalesce(sum(amount) FILTER (WHERE status = 'paid'), 0). The count version, count(*) FILTER (WHERE status = 'paid'), already returns 0 in that case and needs no wrapping.