Subtotals and Grand Totals With ROLLUP, CUBE and GROUPING SETS
How to get detail rows, subtotals and a grand total from one query with ROLLUP, CUBE and GROUPING SETS: how each expands into grouping sets, telling subtotal NULLs from real NULLs with GROUPING(), labelling and sorting totals, partial rollups, and MySQL's WITH ROLLUP.
kvi5hnuCode Sprout team member13 min readOn this page
A report often needs more than one level of totals. A sales summary shows revenue per category and order status, then a subtotal for each category, then a grand total at the bottom. With plain GROUP BY, each level is a separate query: one grouped by category and status, one grouped by category, and one with no grouping at all. You then glue them together with UNION ALL.
SQL has a shorter way. ROLLUP, CUBE and GROUPING SETS are extensions of GROUP BY that compute several groupings in one query, usually in a single pass over the data. This article shows how each one works, how to tell a subtotal row from an ordinary row, and how to label and sort the totals so the report reads well.
The sales data
The examples summarize order lines. To keep the queries short, each runnable first creates a view called sales, a saved query that can be used like a table (article 56 covers views). It joins orders, order lines and products, so it has one row per order line with the line's category, its order's status and the line amount qty * unit_price:
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
There are nine order lines worth 1080.44 in total.
ROLLUP: subtotals along a hierarchy
GROUP BY ROLLUP (category, status) produces the detail groups for each (category, status) pair, then a subtotal for each category, then a grand total:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
\pset null '(null)'
-- Detail rows, a subtotal per category, and a grand total in one query
SELECT category, status, SUM(amount) AS revenue
FROM sales
GROUP BY ROLLUP (category, status)
ORDER BY category, status;
category | status | revenue
----------+-----------+---------
clothing | delivered | 30.00
clothing | shipped | 64.00
clothing | (null) | 94.00
lighting | delivered | 34.50
lighting | shipped | 69.00
lighting | (null) | 103.50
packs | cancelled | 54.00
packs | delivered | 89.95
packs | (null) | 143.95
tents | pending | 489.00
tents | shipped | 249.99
tents | (null) | 738.99
(null) | (null) | 1080.44
(13 rows)
The rows come in three kinds:
- Detail rows, such as clothing / delivered = 30.00. These are what
GROUP BY category, statuswould return. - Subtotal rows, such as clothing / NULL = 94.00. They're grouped by
categoryalone.statusisn't part of the grouping, so it has no single value, and SQL shows NULL. - The grand-total row, NULL / NULL = 1080.44, grouped by nothing: all rows in one group, like a summary query.
ROLLUP is shorthand for a list of grouping sets. A grouping set is one list of columns to group by, and the query returns the groups of every set, one after another, in one result:
GROUP BY ROLLUP (category, status)
-- means
GROUP BY GROUPING SETS ((category, status), (category), ())
ROLLUP removes columns from the right, one at a time: with n columns, it creates n + 1 grouping sets. So the order of the columns matters. ROLLUP (category, status) gives subtotals per category. ROLLUP (status, category) gives subtotals per status instead. Put the columns in the order of the hierarchy you're summarizing, from the broadest to the most detailed: year, month, day, or country, region, city.

The same report without ROLLUP
Here's the report built the long way, with three grouped queries and UNION ALL:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
\pset null '(null)'
-- The same report built by hand: three GROUP BY queries glued together
SELECT category, status, SUM(amount) AS revenue FROM sales GROUP BY category, status
UNION ALL
SELECT category, NULL, SUM(amount) FROM sales GROUP BY category
UNION ALL
SELECT NULL, NULL, SUM(amount) FROM sales
ORDER BY category, status;
category | status | revenue
----------+-----------+---------
clothing | delivered | 30.00
clothing | shipped | 64.00
clothing | (null) | 94.00
lighting | delivered | 34.50
lighting | shipped | 69.00
lighting | (null) | 103.50
packs | cancelled | 54.00
packs | delivered | 89.95
packs | (null) | 143.95
tents | pending | 489.00
tents | shipped | 249.99
tents | (null) | 738.99
(null) | (null) | 1080.44
(13 rows)
The result is identical. Three things make ROLLUP the better choice when your database supports it: the query is shorter, it can't get out of sync when someone changes one branch but not the others, and the database can usually compute all the levels from one scan of the data instead of three. The UNION ALL version is still worth knowing, because it works in SQLite, which has no ROLLUP, and because it shows exactly what ROLLUP means.
Subtotals are recomputed, not added up
Each subtotal is computed from the underlying rows, not from the detail rows above it. For SUM and COUNT that makes no difference. For other aggregates, it matters, and it's the correct behaviour:
AVGin a subtotal row is the average of all the rows in that category, not the average of the detail rows' averages.COUNT(DISTINCT customer_id)in a subtotal row counts each customer once, even if the customer appears in several detail rows. Adding the detail counts would count them twice.MINandMAXgive the smallest and largest value in the whole group.
So you can use any aggregate with ROLLUP and get the right total at every level.
CUBE: every combination
CUBE produces subtotals for every combination of the listed columns. With two columns, that's four grouping sets: both, each one alone, and none:
GROUP BY CUBE (category, status)
-- means
GROUP BY GROUPING SETS ((category, status), (category), (status), ())
Compared with ROLLUP, it adds the set (status), giving a subtotal per status across all categories. With n columns CUBE creates 2 grouping sets, so it grows quickly: four columns give 16. It's meant for cross-tab reports where you want totals in both directions.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
\pset null '(null)'
-- CUBE: every combination, with GROUPING() showing which columns were rolled up
SELECT category,
status,
SUM(amount) AS revenue,
GROUPING(category) AS g_cat,
GROUPING(status) AS g_status,
GROUPING(category, status) AS level
FROM sales
GROUP BY CUBE (category, status)
ORDER BY level, category, status;
category | status | revenue | g_cat | g_status | level
----------+-----------+---------+-------+----------+-------
clothing | delivered | 30.00 | 0 | 0 | 0
clothing | shipped | 64.00 | 0 | 0 | 0
lighting | delivered | 34.50 | 0 | 0 | 0
lighting | shipped | 69.00 | 0 | 0 | 0
packs | cancelled | 54.00 | 0 | 0 | 0
packs | delivered | 89.95 | 0 | 0 | 0
tents | pending | 489.00 | 0 | 0 | 0
tents | shipped | 249.99 | 0 | 0 | 0
clothing | (null) | 94.00 | 0 | 1 | 1
lighting | (null) | 103.50 | 0 | 1 | 1
packs | (null) | 143.95 | 0 | 1 | 1
tents | (null) | 738.99 | 0 | 1 | 1
(null) | cancelled | 54.00 | 1 | 0 | 2
(null) | delivered | 154.45 | 1 | 0 | 2
(null) | pending | 489.00 | 1 | 0 | 2
(null) | shipped | 382.99 | 1 | 0 | 2
(null) | (null) | 1080.44 | 1 | 1 | 3
(17 rows)
The extra four rows, such as NULL / delivered = 154.45, are the per-status totals: everything delivered, across all categories. The grand total appears once, not twice.
GROUPING(): which NULL is which?
In the results so far, NULL in a subtotal row means "all values". That's fine as long as the column has no real NULLs. When it does, the output becomes ambiguous:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
\pset null '(null)'
-- Which NULL is the total? The lantern's brand is NULL too.
SELECT brand, COUNT(*) AS products
FROM products
GROUP BY ROLLUP (brand)
ORDER BY brand;
-- GROUPING() tells them apart; use it for labels and for sorting
SELECT CASE
WHEN GROUPING(brand) = 1 THEN 'All brands'
ELSE COALESCE(brand, '(no brand)')
END AS brand,
COUNT(*) AS products
FROM products
GROUP BY ROLLUP (brand)
ORDER BY GROUPING(brand), brand;
brand | products
---------+----------
Alpina | 2
Kestrel | 2
Lumen | 1
Woolly | 1
(null) | 7
(null) | 1
(6 rows)
brand | products
------------+----------
(no brand) | 1
Alpina | 2
Kestrel | 2
Lumen | 1
Woolly | 1
All brands | 7
(6 rows)
The first query returns two rows with a NULL brand: one is the group of products with no brand (the lantern, 1 product), and the other is the grand total (7 products). You can't tell them apart by looking at the brand column.
The GROUPING(column) function solves this. In each output row, it returns:
- 1 if the column was rolled up, so this row is a subtotal over all its values, and the NULL is a placeholder.
- 0 if the column is part of this row's grouping, so its value, NULL or not, is a real value from the data.
The second query uses it twice:
- For labels. A
CASEshows 'All brands' whenGROUPING(brand) = 1, and otherwise the brand, withCOALESCEturning the real NULL into '(no brand)'. The order of the two tests matters: checkGROUPINGfirst. - For sorting.
ORDER BY GROUPING(brand), brandputs the detail rows first (0) and the total last (1), whatever the brand values are. ThebrandinORDER BYrefers to the output column, the label, so '(no brand)' sorts first because(comes before the letters.
The CUBE example above also used GROUPING with several arguments: GROUPING(category, status) returns a bit pattern, with one bit per argument, where the rightmost argument is the lowest bit. So 0 means a detail row, 1 means status was rolled up, 2 means category was rolled up, and 3 means both, which is the grand total. Sorting by that number orders the rows by level. In Oracle and SQL Server, GROUPING takes a single column, and the multi-argument form is called GROUPING_ID(...). PostgreSQL and MySQL accept the multi-argument GROUPING(...).
Rely on
GROUPING(), not onIS NULL, to find subtotal rows.IS NULLworks only until the data contains a real NULL.
Sorting a rolled-up report
The ROLLUP example sorted with plain ORDER BY category, status, and the subtotals came out in the right places. That only worked because PostgreSQL sorts NULLs last in ascending order. In MySQL, SQL Server and SQLite, NULLs sort first, so the same ORDER BY would put every subtotal above its details and the grand total at the top. The portable way is to sort by GROUPING() at each level:
ORDER BY GROUPING(category), category, GROUPING(status), status
This puts each category's details before its subtotal, and the grand total last, in every database that supports GROUPING.
GROUPING SETS: exactly the totals you want
ROLLUP and CUBE generate grouping sets for you. GROUPING SETS lets you list them yourself, so you get exactly the levels you need and nothing else:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
\pset null '(null)'
-- Only the totals you ask for: per category, per status, and overall
SELECT category, status, COUNT(*) AS lines, SUM(amount) AS revenue
FROM sales
GROUP BY GROUPING SETS ((category), (status), ())
ORDER BY GROUPING(category), category, status;
category | status | lines | revenue
----------+-----------+-------+---------
clothing | (null) | 3 | 94.00
lighting | (null) | 2 | 103.50
packs | (null) | 2 | 143.95
tents | (null) | 2 | 738.99
(null) | cancelled | 1 | 54.00
(null) | delivered | 3 | 154.45
(null) | pending | 1 | 489.00
(null) | shipped | 4 | 382.99
(null) | (null) | 9 | 1080.44
(9 rows)
This returns one block of rows per category, one per status, and the grand total, without the detail rows that CUBE would also include. It's two separate summaries in one result set, which is handy when a dashboard needs several breakdowns of the same data in one round trip.
The notation:
- Each set in the list is in parentheses:
(category),(category, status). ()is the empty set, meaning the grand total.- Plain columns in
GROUP BY, alongsideROLLUP,CUBEorGROUPING SETS, are added to every set. That's how a partial rollup works (next section). - Several
ROLLUP,CUBEorGROUPING SETSitems in oneGROUP BYare combined by taking every combination of their sets, so the number of sets multiplies. PostgreSQL 14 addedGROUP BY DISTINCTto drop the duplicate sets this can produce.
Partial rollups and filtering totals
Sometimes you want subtotals but no grand total, or only the totals and not the details:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
\pset null '(null)'
-- Partial rollup: subtotals per category, but no grand total
SELECT category, status, SUM(amount) AS revenue
FROM sales
GROUP BY category, ROLLUP (status)
ORDER BY category, GROUPING(status), status;
-- Keep only the subtotal rows with HAVING
SELECT category, SUM(amount) AS revenue
FROM sales
GROUP BY ROLLUP (category, status)
HAVING GROUPING(status) = 1
ORDER BY GROUPING(category), category;
category | status | revenue
----------+-----------+---------
clothing | delivered | 30.00
clothing | shipped | 64.00
clothing | (null) | 94.00
lighting | delivered | 34.50
lighting | shipped | 69.00
lighting | (null) | 103.50
packs | cancelled | 54.00
packs | delivered | 89.95
packs | (null) | 143.95
tents | pending | 489.00
tents | shipped | 249.99
tents | (null) | 738.99
(12 rows)
category | revenue
----------+---------
clothing | 94.00
lighting | 103.50
packs | 143.95
tents | 738.99
(null) | 1080.44
(5 rows)
In the first query, GROUP BY category, ROLLUP (status) adds category to each of the sets that ROLLUP (status) creates, giving (category, status) and (category). There's no () set, so no grand total. This is called a partial rollup.
The second query filters with HAVING GROUPING(status) = 1, which keeps only the rows where status was rolled up: the category subtotals and the grand total. GROUPING can be used in HAVING, SELECT and ORDER BY, but not in WHERE, because WHERE runs before any grouping exists. To filter the rows that go into the totals, use WHERE as usual: WHERE status <> 'cancelled' would remove the cancelled line from every detail row and every total.
Support in each database
| Database | ROLLUP | CUBE | GROUPING SETS | GROUPING() |
|---|---|---|---|---|
| PostgreSQL | yes (9.5+) | yes | yes | yes, several arguments |
| Oracle | yes | yes | yes | yes, plus GROUPING_ID and GROUP_ID |
| SQL Server | yes | yes | yes | yes, plus GROUPING_ID |
| MySQL | WITH ROLLUP; ROLLUP (...) in recent 9.x | HeatWave only | HeatWave only (9.6+) | yes, since 8.0.1 |
| SQLite | no | no | no | no |
MySQL's traditional syntax puts the modifier after the column list:
SELECT category, status, SUM(amount)
FROM sales
GROUP BY category, status WITH ROLLUP;
It means the same as ROLLUP (category, status). MySQL 8.0 also made WITH ROLLUP work together with ORDER BY and added GROUPING(), so the portable sorting pattern above works there too. MySQL 9.6, the version these examples were checked against, also accepts the standard GROUP BY ROLLUP (category) form. It parses CUBE and GROUPING SETS, but runs them only on the HeatWave engine, and the community server rejects them with an error. In MySQL and SQLite, use UNION ALL of several grouped queries for the other combinations.
SQL Server also accepts an older WITH ROLLUP and WITH CUBE syntax, which Microsoft keeps only for backward compatibility. Use the standard form there.
What's current
- PostgreSQL 14 added
GROUP BY DISTINCT, which removes duplicate grouping sets when severalROLLUPorCUBEitems are combined. - MySQL 9.6 brought
GROUPING SETSto MySQL HeatWave. The community server in 9.6 acceptsGROUP BY ROLLUP (...)but notCUBEorGROUPING SETS, so check your server before relying on them. - The standard features (
ROLLUP,CUBE,GROUPING SETSandGROUPING) have been stable in PostgreSQL, Oracle and SQL Server for many years. SQLite still has none of them.
Common questions
Why does my report show NULL in the subtotal rows?
In a subtotal row, the rolled-up column doesn't have a single value, so SQL fills it with NULL. Replace it with a label using CASE WHEN GROUPING(col) = 1 THEN 'Total' ELSE ... END.
How do I tell a subtotal row from a group whose value really is NULL?
Use GROUPING(col). It's 1 in subtotal rows and 0 in ordinary rows, whatever the column's value.
What's the difference between ROLLUP and CUBE?
ROLLUP (a, b) gives subtotals along one hierarchy: (a, b), (a) and (). CUBE (a, b) gives every combination: (a, b), (a), (b) and ().
Does the column order matter?
In ROLLUP, yes: ROLLUP (a, b) gives subtotals per a, and ROLLUP (b, a) gives subtotals per b. In CUBE and GROUPING SETS, the order doesn't change which totals you get.
Are subtotals correct for AVG and COUNT(DISTINCT ...)?
Yes. Every subtotal is computed from the underlying rows, so averages and distinct counts are correct at every level.
How do I put the grand total at the bottom?
Sort by GROUPING() first: ORDER BY GROUPING(category), category. Rows with 1, the totals, sort after rows with 0.
Can I get only the totals, without the detail rows?
Yes. Use GROUPING SETS with just the levels you want, or filter with HAVING GROUPING(col) = 1.
How do I get subtotals in SQLite?
Write one grouped query per level and combine them with UNION ALL, putting NULL or a label in the columns that aren't grouped, as in the second example.
Summary
ROLLUP,CUBEandGROUPING SETScompute several levels of grouping in one query and return them in one result.ROLLUP (a, b)means the grouping sets (a, b), (a) and (): details, subtotals and a grand total. Column order defines the hierarchy.CUBE (a, b)means every combination: (a, b), (a), (b) and ().GROUPING SETSlists the sets explicitly.()is the grand total, and plain columns next to them are added to every set.- In subtotal rows, rolled-up columns are NULL.
GROUPING(col)returns 1 for those and 0 for real values. Use it for labels, sorting and filtering. - Subtotals are recomputed from the underlying rows, so every aggregate is correct at every level.
- MySQL uses
WITH ROLLUPand has noCUBEorGROUPING SETSoutside HeatWave. SQLite has none of these, so useUNION ALLthere.
Practice questions
Which grouping sets does GROUP BY ROLLUP (year, month, day) produce, and how many rows of each kind would you expect?
Answer
Four sets: (year, month, day), (year, month), (year) and (). You get one row per day that has data, one subtotal per month, one subtotal per year, and a single grand total.
Write a query on the sales view that returns revenue per status, plus a final row labelled 'All statuses' with the total. The total must be last.
Answer
SELECT CASE WHEN GROUPING(status) = 1 THEN 'All statuses' ELSE status END AS status,
SUM(amount) AS revenue
FROM sales
GROUP BY ROLLUP (status)
ORDER BY GROUPING(status), status;
On the course data, this returns cancelled 54.00, delivered 154.45, pending 489.00, shipped 382.99 and All statuses 1080.44. Sorting by GROUPING(status) first puts the total last in every database.
A rolled-up report uses WHERE category IS NULL to find the grand-total row, and it works. Why is that fragile, and what should it use instead?
Answer
IS NULL can't tell a subtotal's placeholder NULL from a real NULL in the data. If a product without a category is ever added, its group also has a NULL category and is mistaken for a total. Test GROUPING(category) = 1 instead, which is 1 only when the column was rolled up.
What's the difference between GROUP BY CUBE (category, status) and GROUP BY GROUPING SETS ((category), (status))?
Answer
CUBE produces four sets: the detail rows (category, status), the subtotals per category, the subtotals per status, and the grand total. The GROUPING SETS version produces only the two subtotal levels: one row per category and one row per status, with no detail rows and no grand total.
Each category subtotal in a report uses AVG(amount). Is it the average of the detail rows' averages?
Answer
No. It's the average of all the order lines in the category. For clothing, the lines are 48.00, 30.00 and 16.00 (three lines in the delivered and shipped groups), so the subtotal average is 94.00 / 3 = 31.33. The average of the two detail averages, delivered 30.00 and shipped 32.00, would be 31.00, which is wrong. ROLLUP always aggregates the underlying rows.
How would you produce the category subtotals and grand total of a ROLLUP (category, status) report in SQLite?
Answer
SQLite has no ROLLUP, so combine grouped queries:
SELECT category, revenue
FROM (SELECT category, SUM(amount) AS revenue FROM sales GROUP BY category
UNION ALL
SELECT NULL, SUM(amount) FROM sales) AS report
ORDER BY category IS NULL, category;
category IS NULL is 0 for the category rows and 1 for the total, so the total sorts last. The union is wrapped in a derived table because SQLite only allows plain result columns, not expressions, in the ORDER BY of a UNION. Add a third branch grouped by category, status if you also need the detail rows.
Previous: GROUP BY and HAVING: Summarizing Groups of Rows
Next: Conditional Aggregation in SQL: CASE Inside Aggregates and FILTER

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.