Subtotals and Grand Totals with ROLLUP in SQL
ROLLUP adds total rows to a grouped result, so a report carries its own subtotals and grand total.
A grouped report often needs a total row at the bottom.
GROUP BY ROLLUP (…)
adds it for you: alongside the normal per-group rows, it emits an extra row
that aggregates across all groups.
In that total row, the grouped column is
NULL
because there is no single category it belongs to. Use
grouping()
to distinguish that generated null from a real null in the source data, then
label and sort the total row deliberately.
select region, sum(amount) as total
from sales
group by rollup (region)
With more than one grouping column,
ROLLUP (a, b)
also produces
per-a
subtotals, not just the grand total. You get a full hierarchy of totals from
one query.
Schema · Garden Shop Tables · order_items, products, categories 3 tables
One row per line item within an order.
One row per product, with price, cost, and inventory levels.
Lookup table of product categories.
Report total revenue (quantity * unit_price) per category, in
alphabetical order, with a grand-total row at the bottom
labeled 'All categories'. Return category and
revenue.
Run your query to inspect the result.
Expected answer
- Columns: category, revenue.
- Rows: 8 category rows plus 1 grand-total row (9 total).
- The 'All categories' revenue equals the sum of the eight category rows.
Related
COUNT, SUM, AVG, MIN, MAX, GROUP BY, and HAVING.
COUNT, SUM, AVG, GROUP BY, and HAVING.
Practice aggregate reports, HAVING, and answer shape.
Avoid truncating fractional results.
Filter groups with HAVING, rows with WHERE.
Searched and simple CASE patterns.