← Back to SQL, page 4

sql-0079 · Hard senior

How do you add subtotals and a grand total to a grouped report? Explain ROLLUP and how to emulate it.

GROUP BY ROLLUP (a, b) returns the normal (a, b) groups plus a subtotal row per a and one grand-total row, with NULL in the rolled-up columns. PostgreSQL, MySQL, SQL Server and Oracle support it; SQLite does not, so there you UNION ALL the detail, subtotal and total queries. GROUPING() tells a rolled-up NULL apart from a real NULL.

Full answer

A sales report often wants detail rows, a subtotal per country and a grand total. ROLLUP produces all three in one query.

sql
CREATE TABLE sales (country TEXT, product TEXT, amount INTEGER);
INSERT INTO sales VALUES ('India','Pen',10),('India','Bag',30),('India','Pen',5),('Spain','Pen',8),('Spain','Lamp',25);

PostgreSQL:

sql
SELECT country, product, SUM(amount) AS total
FROM sales
GROUP BY ROLLUP (country, product)
ORDER BY country NULLS LAST, product NULLS LAST;
countryproducttotal
IndiaBag30
IndiaPen15
IndiaNULL45
SpainLamp25
SpainPen8
SpainNULL33
NULLNULL78

Rows with product NULL are the country subtotals, and the row with both NULL is the grand total. GROUPING(col) returns 1 when the NULL was produced by the rollup, which matters if the data itself can contain NULLs:

sql
SELECT country, product, GROUPING(country) AS g_country, GROUPING(product) AS g_product, SUM(amount) AS total
FROM sales
GROUP BY ROLLUP (country, product)
ORDER BY country NULLS LAST, product NULLS LAST;
countryproductg_countryg_producttotal
IndiaBag0030
IndiaPen0015
IndiaNULL0145
SpainLamp0025
SpainPen008
SpainNULL0133
NULLNULL1178

SQLite has no ROLLUP:

sql
SELECT country, product, SUM(amount) FROM sales GROUP BY ROLLUP (country, product);  -- error on purpose
text
Error: no such function: ROLLUP

The emulation is a UNION ALL of the three levels:

sql
SELECT country, product, total FROM (
  SELECT country, product, SUM(amount) AS total, 0 AS lvl FROM sales GROUP BY country, product
  UNION ALL
  SELECT country, NULL,    SUM(amount),          1        FROM sales GROUP BY country
  UNION ALL
  SELECT NULL,    NULL,    SUM(amount),          2        FROM sales
)
ORDER BY lvl = 2, country, lvl, product;
countryproducttotal
IndiaBag30
IndiaPen15
IndiaNULL45
SpainLamp25
SpainPen8
SpainNULL33
NULLNULL78

The extra lvl column keeps the subtotal under its details and the total at the end. Related tools: GROUPING SETS ((country), (product), ()) lets you pick any combination of groupings, and CUBE (a, b) produces every combination. Each grouping level costs another aggregation pass in the emulation, so on large tables a single ROLLUP query on an engine that supports it is cheaper.

sql
CREATE TABLE sales (country TEXT, product TEXT, amount INTEGER);
INSERT INTO sales VALUES ('India','Pen',10),('India','Bag',30),('India','Pen',5),('Spain','Pen',8),('Spain','Lamp',25);

-- error on purpose
SELECT country, product, SUM(amount) FROM sales GROUP BY ROLLUP (country, product);

SELECT country, product, total FROM (
  SELECT country, product, SUM(amount) AS total, 0 AS lvl FROM sales GROUP BY country, product
  UNION ALL
  SELECT country, NULL,    SUM(amount),          1        FROM sales GROUP BY country
  UNION ALL
  SELECT NULL,    NULL,    SUM(amount),          2        FROM sales
)
ORDER BY lvl = 2, country, lvl, product;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • ROLLUP adds subtotal and grand-total rows
  • Rolled-up columns appear as NULL; GROUPING() identifies them
  • SQLite lacks ROLLUP; emulate with UNION ALL of each level
  • GROUPING SETS and CUBE generalise the idea

Common mistakes

  • Confusing a subtotal NULL with a real NULL in the data
  • Sorting so subtotal rows appear above their details

Follow-ups

  • How would you label subtotal rows as 'All products'?
  • What does CUBE (country, product) add on top of ROLLUP?

Tips

  • Show how you sort the result so subtotals sit under their group