ROLLUP Adds Hierarchical Subtotals

Aggregate sales with ROLLUP to get region and month subtotals plus a grand total, then mark total rows with the GROUPING function.

SqlData Integrity

Code

snippet
CREATE TABLE sales (
  region text NOT NULL,
  month date NOT NULL,
  amount numeric(10, 2) NOT NULL
);

INSERT INTO sales (region, month, amount)
VALUES
  ('north', '2026-01-01', 120.00),
  ('north', '2026-02-01', 80.00),
  ('south', '2026-01-01', 200.00),
  ('south', '2026-02-01', 50.00);

SELECT region,
       month,
       sum(amount) AS total,
       GROUPING(region) AS region_is_total,
       GROUPING(month) AS month_is_total
FROM sales
GROUP BY ROLLUP (region, month)
ORDER BY region NULLS LAST, month NULLS LAST;

-- ROLLUP expands to these grouping sets.
SELECT region, month, sum(amount) AS total
FROM sales
GROUP BY GROUPING SETS ((region, month), (region), ())
ORDER BY region NULLS LAST, month NULLS LAST;

How the snippet works

What runs here is SELECT / INSERT / CREATE — sales are the objects involved.

Breaking the statements into their working parts: SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

Applying it

Run the statement against the sales table.

Statements that matter

SELECT region,
month,
sum(amount) AS total,
GROUPING(region) AS region_is_total,
GROUPING(month) AS month_is_total
FROM sales
GROUP BY ROLLUP (region, month)
ORDER BY region NULLS LAST, month NULLS LAST;
SELECT region, month, sum(amount) AS total
FROM sales
GROUP BY GROUPING SETS ((region, month), (region), ())
ORDER BY region NULLS LAST, month NULLS LAST;
INSERT INTO sales (region, month, amount)
VALUES
('north', '2026-01-01', 120.00),
('north', '2026-02-01', 80.00),
('south', '2026-01-01', 200.00),
('south', '2026-02-01', 50.00);

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`sales` — referenced directly, no join needed.