Example 1
Show total sales per region plus a grand total row
East contributed 300 + 200 = 500 and West contributed 150 + 250 = 400. ROLLUP adds a third row where region is NULL (the rollup placeholder) and total is 900 — the sum of all rows. GROUPING(region) returns 0 for the East and West rows and 1 for the rollup row, which the ORDER BY uses to push the grand total to the end.
CREATE TABLE sales (region VARCHAR(20), amount INT);
INSERT INTO
sales
VALUES
('East', 300),
('East', 200),
('West', 150),
('West', 250);SELECT
region,
SUM(amount) AS total
FROM
sales
GROUP BY
region
WITH
ROLLUP
ORDER BY
GROUPING(region),
region;| region | total |
|---|---|
| East | 500 |
| West | 400 |
| NULL | 900 |
CREATE TABLE sales (region VARCHAR(20), amount INT);
INSERT INTO
sales
VALUES
('East', 300),
('East', 200),
('West', 150),
('West', 250);SELECT
region,
SUM(amount) AS total
FROM
sales
GROUP BY
ROLLUP (region)
ORDER BY
GROUPING(region),
region;| region | total |
|---|---|
| East | 500 |
| West | 400 |
| NULL | 900 |
MySQL and MariaDB use `GROUP BY col WITH ROLLUP`. PostgreSQL and SQL Server use `GROUP BY ROLLUP(col)`. The output is identical across supported engines. `ORDER BY GROUPING(region), region` places normal rows first (GROUPING = 0) and the grand-total row last (GROUPING = 1).