Skip to main content

GROUP BY with ROLLUP

WITH ROLLUP extends grouped results with subtotal and grand total rows, which is useful for financial and operational reports.

Report Structure

LevelExample columnsRow meaning
Detail groupregion, product_lineMetric per leaf group
Subtotalregion, NULLMetric per region
Grand totalNULL, NULLMetric across all rows

Example Query

SELECT region,
product_line,
SUM(total_amount) AS revenue
FROM sales
GROUP BY region, product_line WITH ROLLUP;

Display-Friendly Labels

SELECT COALESCE(region, 'ALL_REGIONS') AS region,
COALESCE(product_line, 'SUBTOTAL_OR_TOTAL') AS product_line,
SUM(total_amount) AS revenue
FROM sales
GROUP BY region, product_line WITH ROLLUP;
regionproduct_linerevenue
EUHardware45000.00
EUSoftware61000.00
EUSUBTOTAL_OR_TOTAL106000.00
ALL_REGIONSSUBTOTAL_OR_TOTAL312500.00

Common Pitfalls

PitfallConsequencePrevention
Treating subtotal rows as regular groupsWrong downstream calculationsDetect NULL rollup keys and label them explicitly
Applying filters in client onlyInconsistent reporting outputKeep business filters in SQL query
Sorting without handling rollup rowsTotals appear in unexpected orderUse explicit ORDER BY strategy for report rendering

Quick Reference

SELECT a, SUM(v) FROM t GROUP BY a WITH ROLLUP;
SELECT a, b, COUNT(*) FROM t GROUP BY a, b WITH ROLLUP;
SELECT COALESCE(a, 'TOTAL') AS a, SUM(v) FROM t GROUP BY a WITH ROLLUP;

What's Next