Subtotals and grand totals in one SQL query: how GROUP BY ROLLUP worksNote · digest for November 24
Security engineer's desk with a studio still life of cryptographic security artifacts and a clean verification monitor free of third-party trackers
Note3 sections≈ 4 min

Subtotals and grand totals in one SQL query: how GROUP BY ROLLUP works

How do you pull sales by city, subtotals by country, month, and quarter, plus a grand total for the year—all in a single query?

Usually, teams stitch several GROUP BY queries together with UNION ALL and pad missing columns with NULL. Change one WHERE filter or add a JOIN, and you have to update five branches while the database scans the table over and over. Standard SQL solves hierarchical aggregation (summing across nested levels at once) with GROUP BY ROLLUP, computing every total in a single pass.

How ROLLUP folds levels from right to left

Whenever your data forms a tree—time (year, quarter, month, day), geography (country, region, city), or org structure (company, department, team)—ROLLUP collapses the column list from right to left.

For N columns, the database computes N + 1 grouping sets: first the full list, then dropping the rightmost column, then the next one, all the way down to the empty set () for the grand total. Under the hood, ROLLUP(a, b, c) equals GROUPING SETS ((a, b, c), (a, b), (a), ()). Its sibling CUBE generates all 2^N combinations, which helps when data has no strict hierarchy, though row counts grow fast.

-- From coarse to fine: year -> quarter -> month -> country -> city
SELECT
    EXTRACT(YEAR FROM sale_date)::int    AS sale_year,
    EXTRACT(QUARTER FROM sale_date)::int AS sale_quarter,
    EXTRACT(MONTH FROM sale_date)::int   AS sale_month,
    country, city, SUM(amount) AS total_sales
FROM sales
WHERE sale_date >= DATE '2025-01-01'
  AND sale_date <  DATE '2026-01-01'
GROUP BY ROLLUP (
    EXTRACT(YEAR FROM sale_date)::int,
    EXTRACT(QUARTER FROM sale_date)::int,
    EXTRACT(MONTH FROM sale_date)::int,
    country, city
)
ORDER BY sale_year NULLS LAST, sale_quarter NULLS LAST,
         sale_month NULLS LAST, country NULLS LAST, city NULLS LAST;

Column order changes everything here: if you write ROLLUP(city, country), the database sums same-named cities across all countries at once. In PostgreSQL, you can also group two fields into one level with parentheses (ROLLUP(a, (b, c), d)) or calculate subtotals inside departments without a table-wide grand total: GROUP BY department, ROLLUP(country, city).

The main trap: subtotal NULLs and GROUPING()

In subtotal rows, the database puts NULL into every collapsed column. If some orders in your table already have an empty city, a naive COALESCE(city, 'All cities') mixes broken records into the country subtotal.

GROUPING() separates collapsed columns from real NULL values: it returns 1 for a subtotal and 0 for an actual value (including a real NULL). With multiple arguments, it returns a bitmask where the lowest bit belongs to the rightmost column.

Grouping setWhat the row aggregateslevel_mask
(sale_year, country, city)Detailed sales per city0
(sale_year, country)Country subtotal for the year1
(sale_year)Yearly subtotal3
()Grand total across the entire result7
-- Safe labels and sorting for (sale_year, country, city)
SELECT
    CASE WHEN GROUPING(sale_year) = 1 THEN 'ALL YEARS'
         ELSE sale_year::text END        AS year_label,
    CASE WHEN GROUPING(country) = 1 THEN 'All countries'
         ELSE COALESCE(country, '—') END AS country_label,
    CASE WHEN GROUPING(city) = 1 THEN 'All cities'
         ELSE COALESCE(city, '—') END    AS city_label,
    SUM(amount)                          AS total_sales,
    GROUPING(sale_year, country, city)   AS level_mask
FROM sales_summary
GROUP BY ROLLUP (sale_year, country, city)
ORDER BY GROUPING(sale_year), sale_year,
         GROUPING(country), country, GROUPING(city), city;

ROLLUP itself doesn't guarantee row order, especially in PostgreSQL, so an explicit ORDER BY with GROUPING(...) is essential. You can also drop unwanted levels using HAVING GROUPING(col) = .... On an empty table, the () set in PostgreSQL still returns one grand-total row, just like a plain SELECT SUM(amount) without GROUP BY.

How it works in MySQL and other databases

Standard GROUP BY ROLLUP (...) works in PostgreSQL, SQL Server, Oracle, DuckDB, and ClickHouse. In MySQL, you append WITH ROLLUP at the end of GROUP BY:

-- In MySQL, WITH ROLLUP goes after the column list
SELECT
    IF(GROUPING(country) = 1, 'All countries',
       COALESCE(country, '—')) AS country,
    IF(GROUPING(city) = 1, 'All cities',
       COALESCE(city, '—'))    AS city,
    SUM(amount) AS total_sales
FROM sales_summary
GROUP BY country, city WITH ROLLUP;

In MySQL, WITH ROLLUP folds the entire column list linearly from right to left, so you can't directly mix regular grouping with a partial ROLLUP. However, GROUPING() works the exact same way and cleanly separates subtotals from real NULL values in your table.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 4