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.
Code
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which tables does this file reference?
- `sales` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.