Subtotals and totals: ROLLUP
GROUP BY a, b WITH ROLLUP adds a subtotal row after each a (where b is NULL) and a grand total row at the end (where both are NULL). GROUPING(col) is 1 when the row was added by the rollup. Name the rows with CASE WHEN GROUPING(col) = 1 THEN 'Total' …, and use ORDER BY GROUPING(col) to put the total last.
The boss wants a table of sales by category, with a "Total" row at the bottom. For a table by category and quarter, each category also needs a "subtotal". Writing several queries and gluing them together is a pain. WITH ROLLUP lets GROUP BY work out these summary rows along the way.
Add a total row
In this step you add two words, WITH ROLLUP, after GROUP BY:
1SELECT p.category, SUM(oi.qty * oi.price) AS sales2FROM orders AS o3JOIN order_items AS oi ON oi.order_id = o.id4JOIN products AS p ON p.id = oi.product_id5WHERE o.status = 'paid'6GROUP BY p.category WITH ROLLUP;
| category | sales |
|---|---|
| food | 520 |
| home | 1596 |
| office | 484 |
| tech | 3823 |
| NULL | 6423 |
After the 4 categories there's one more row: category is NULL and sales is 6423, exactly the sales for the whole year. That's the total row: ROLLUP takes "grouped by category" one level further up, into "everything". Everything doesn't belong to any one category, so the category cell is NULL.
Group by order status and add WITH ROLLUP. What's n in the last row?
1SELECT status, COUNT(*) AS n2FROM orders3GROUP BY status WITH ROLLUP;
orders. In the total row, COUNT counts everything, not how many groups there are.Subtotals on two levels
In this step you group by two columns. GROUP BY category, quarter WITH ROLLUP rolls up level by level from right to left: first it adds a subtotal row after each category (where the quarter is NULL), and at the end a grand total row (where both columns are NULL). Look at just two categories first:
1SELECT p.category, QUARTER(o.order_date) AS q, SUM(oi.qty * oi.price) AS sales2FROM orders AS o3JOIN order_items AS oi ON oi.order_id = o.id4JOIN products AS p ON p.id = oi.product_id5WHERE o.status = 'paid'6 AND p.category IN ('food', 'office')7GROUP BY p.category, q WITH ROLLUP;
| category | q | sales |
|---|---|---|
| food | 1 | 52 |
| food | 2 | 74 |
| food | 3 | 216 |
| food | 4 | 178 |
| food | NULL | 520 |
| office | 1 | 32 |
| office | 2 | 52 |
| office | 3 | 206 |
| office | 4 | 194 |
| office | NULL | 484 |
| NULL | NULL | 1004 |
| category | q | sales |
|---|---|---|
| food | 1 | 52 |
| food | … | … |
| food | 4 | 178 |
| food | NULL | 520 |
| office | 1 | 32 |
| office | … | … |
| office | NULL | 484 |
| NULL | NULL | 1004 |
There are 4 categories, and each has sales in all 4 quarters. How many rows does GROUP BY category, q WITH ROLLUP give in all?
1-- plain groups: 4 × 4 = 16 rows2-- one subtotal row per category: 4 rows3-- one grand total row at the end: 1 row4-- rows in all
ROLLUP only rolls up from right to left, so it doesn't also add "a subtotal for each quarter across categories". Adding one for every combination is what CUBE does in other databases.Which NULL is the total
In this step you run into a real problem. Lesson 1 showed that 2 users didn't fill in their city, so their city is NULL. Add ROLLUP by city:
1SELECT u.city, COUNT(*) AS orders2FROM orders AS o3JOIN users AS u ON u.id = o.user_id4WHERE o.status = 'paid'5GROUP BY u.city WITH ROLLUP6ORDER BY GROUPING(u.city), orders DESC;
| city | orders |
|---|---|
| Rio | 28 |
| Lisbon | 25 |
| Madrid | 24 |
| São Paulo | 20 |
| Porto | 13 |
| NULL | 5 |
| NULL | 115 |
At the bottom there are two NULL rows: the one with 5 orders is "people who didn't fill in a city", and only the one with 115 orders is the total. Looking at NULL alone, you can't tell them apart.
GROUPING(col) exists to answer exactly this: it gives 1 if the row was added by ROLLUP, and 0 if it's a plain group. With it, you can give every row a clear name:
1SELECT CASE2 WHEN GROUPING(u.city) = 1 THEN 'Total'3 ELSE COALESCE(u.city, '(not set)')4 END AS city,5 COUNT(*) AS orders6FROM orders AS o7JOIN users AS u ON u.id = o.user_id8WHERE o.status = 'paid'9GROUP BY u.city WITH ROLLUP10ORDER BY GROUPING(u.city), orders DESC;
| city | orders |
|---|---|
| Rio | 28 |
| Lisbon | 25 |
| Madrid | 24 |
| São Paulo | 20 |
| Porto | 13 |
| (not set) | 5 |
| Total | 115 |
Ask GROUPING first, then use COALESCE for the real empty values, and don't swap the order: if COALESCE came first, the total row would also be called "(not set)".
The query that totals by city ends with ORDER BY GROUPING(u.city), orders DESC. What does it do?
GROUPING from small to large puts 0 first and 1 last, so the total is always at the bottom, the way a report should look. Rows that are all 0 are then sorted by orders from most to fewest.Make it a report
In this step you put everything together and build a table you can hand straight to the boss.
Sales report by city
✓For each city, count the paid orders and add up the sales, with a total row at the bottom. Three columns: city (write Total in the total row and (not set) for people with no city), orders and sales. Sort the plain rows by orders from most to fewest, with the total last.
| city | orders | sales |
|---|---|---|
| Rio | 28 | 2253 |
| Lisbon | 25 | 1050 |
| Madrid | 24 | 1422 |
| São Paulo | 20 | 1142 |
| Porto | 13 | 363 |
| (not set) | 5 | 193 |
| Total | 115 | 6423 |
1SELECT u.city, COUNT(*) AS orders, SUM(o.amount) AS sales2FROM orders AS o3JOIN users AS u ON u.id = o.user_id4WHERE o.status = 'paid'5GROUP BY u.city;
Other databases: PostgreSQL, SQL Server and Oracle write GROUP BY ROLLUP (category, q), which means the same thing. MySQL 8 only accepts the GROUP BY category, q WITH ROLLUP form. Those databases also have CUBE (subtotals for every combination) and GROUPING SETS (you list which summaries you want), which MySQL doesn't have.
What you learned
GROUP BY … WITH ROLLUPworks out summary rows on top of the plain groups. The columns that were summed up areNULL.- Grouping by two columns rolls up from right to left: a subtotal row for each value of the first column, and a grand total at the end.
- When the data already has
NULLin it, useGROUPING(col)to tell them apart: 1 is a summary row, 0 is a plain row. - To name the rows: first
CASE WHEN GROUPING(col) = 1 THEN 'Total', thenCOALESCEfor the real empty values. ORDER BY GROUPING(col), …puts the total last.- Other databases write
GROUP BY ROLLUP (…).