ROLLUP, CUBE and GROUPING SETS

Updated · 8 min read
hardPostgreSQL 18sqlrollupcubegrouping-setssubtotalsreporting

ROLLUP, CUBE and GROUPING SETS in SQL are extensions of GROUP BY that compute several groupings in one query, so that a single result contains detail rows, subtotals and a grand total. They are used for reports like "payments by student and method, with each student's subtotal and an overall total". Without them, that report needs three queries joined with UNION ALL. In this lesson, we will learn all three, and the GROUPING() function, which tells a subtotal row apart from a row whose value really is NULL.

In One Minute

  • GROUP BY ROLLUP (a, b) gives groups for (a, b), then (a) subtotals, then () the grand total.
  • GROUP BY CUBE (a, b) gives every combination: (a, b), (a), (b) and ().
  • GROUP BY GROUPING SETS ((a), (b), ()) lists exactly the groupings you want.
  • In total rows, the rolled-up columns show NULL.
  • GROUPING(col) is 1 when col was rolled up in that row, and 0 otherwise.

Syntax

SQL
GROUP BY ROLLUP (col1, col2)
GROUP BY CUBE (col1, col2)
GROUP BY GROUPING SETS ((col1, col2), (col1), ())
ClauseGroupings produced for (student_id, method)
ROLLUP(student_id, method), (student_id), ()
CUBE(student_id, method), (student_id), (method), ()
GROUPING SETS (...)exactly the ones listed

ROLLUP: Subtotals and a Grand Total

The following query totals payments by student and method, with each student's subtotal and the grand total:

SQL▶ Try it
SELECT student_id, method, sum(amount_usd) AS total
FROM payments
GROUP BY ROLLUP (student_id, method)
ORDER BY student_id NULLS LAST, method NULLS LAST;
Output
 student_id | method |  total
------------+--------+---------
        101 | card   | 1250.00
        101 | check  |  250.00
        101 | NULL   | 1700.00
        101 | NULL   |  200.00
        103 | card   |  225.00
        103 | check  |  225.00
        103 | NULL   |  450.00
       NULL | NULL   | 2150.00
(8 rows)

Explanation: ROLLUP (student_id, method) produces three levels. The detail rows group by both columns. The subtotal rows group by student_id alone, with method shown as NULL: Srihitha's subtotal is $1,700.00. The last row groups by nothing, with both columns NULL: the grand total, $2,150.00.

But look at Srihitha's two rows with method NULL: $200.00 and $1,700.00. One is her real payment with no recorded method; the other is her subtotal. The result alone can't tell them apart.

Detail rows by student and method, a subtotal per student, and one grand total row

GROUPING(): Telling Totals from NULL Data

GROUPING(column) returns 1 in rows where that column was rolled up into a total, and 0 where it holds a real value.

SQL▶ Try it
SELECT student_id, method, sum(amount_usd) AS total,
       GROUPING(student_id) AS student_rolled_up,
       GROUPING(method) AS method_rolled_up
FROM payments
GROUP BY ROLLUP (student_id, method)
ORDER BY student_id NULLS LAST, GROUPING(method), method NULLS LAST;
Output
 student_id | method |  total  | student_rolled_up | method_rolled_up
------------+--------+---------+-------------------+------------------
        101 | card   | 1250.00 |                 0 |                0
        101 | check  |  250.00 |                 0 |                0
        101 | NULL   |  200.00 |                 0 |                0
        101 | NULL   | 1700.00 |                 0 |                1
        103 | card   |  225.00 |                 0 |                0
        103 | check  |  225.00 |                 0 |                0
        103 | NULL   |  450.00 |                 0 |                1
       NULL | NULL   | 2150.00 |                 1 |                1
(8 rows)

Explanation: The $200.00 row has method_rolled_up 0: its NULL is real data, a payment with no method. The $1,700.00 row has 1: its NULL means "all methods". With GROUPING() we can label the total rows in words:

SQL▶ Try it
SELECT CASE WHEN GROUPING(student_id) = 1 THEN 'All students' ELSE student_id::text END AS student,
       CASE WHEN GROUPING(method) = 1 THEN 'All methods' ELSE coalesce(method, '(none)') END AS method,
       sum(amount_usd) AS total
FROM payments
GROUP BY ROLLUP (student_id, method)
ORDER BY GROUPING(student_id), student_id, GROUPING(method), method NULLS LAST;
Output
   student    |   method    |  total
--------------+-------------+---------
 101          | (none)      |  200.00
 101          | card        | 1250.00
 101          | check       |  250.00
 101          | All methods | 1700.00
 103          | card        |  225.00
 103          | check       |  225.00
 103          | All methods |  450.00
 All students | All methods | 2150.00
(8 rows)
Two rows with method NULL: GROUPING 0 is a real missing method, GROUPING 1 is the student subtotal

CUBE: Every Combination

CUBE (a, b) adds subtotals for every combination, including b alone. Totals by student, by method, and overall:

SQL▶ Try it
SELECT student_id, method, sum(amount_usd) AS total
FROM payments
GROUP BY CUBE (student_id, method)
ORDER BY GROUPING(student_id), student_id, GROUPING(method), method NULLS LAST;
Output
 student_id | method |  total
------------+--------+---------
        101 | card   | 1250.00
        101 | check  |  250.00
        101 | NULL   |  200.00
        101 | NULL   | 1700.00
        103 | card   |  225.00
        103 | check  |  225.00
        103 | NULL   |  450.00
       NULL | card   | 1475.00
       NULL | check  |  475.00
       NULL | NULL   |  200.00
       NULL | NULL   | 2150.00
(11 rows)

Explanation: Compared with ROLLUP, CUBE adds the per-method totals across all students: card $1,475.00, check $475.00, and no method $200.00. With two columns, CUBE gives 4 groupings; with three, 8. It grows quickly, so use it when you really want every cross-total.

GROUPING SETS: Exactly the Totals You Want

GROUPING SETS lists the groupings directly. Per-student totals, per-method totals and the grand total, without the detail rows:

SQL▶ Try it
SELECT CASE WHEN GROUPING(student_id) = 1 THEN 'all' ELSE student_id::text END AS student,
       CASE WHEN GROUPING(method) = 1 THEN 'all' ELSE coalesce(method, '(none)') END AS method,
       sum(amount_usd) AS total
FROM payments
GROUP BY GROUPING SETS ((student_id), (method), ())
ORDER BY GROUPING(student_id), student_id, GROUPING(method), method NULLS LAST;
Output
 student | method |  total
---------+--------+---------
 101     | all    | 1700.00
 103     | all    |  450.00
 all     | (none) |  200.00
 all     | card   | 1475.00
 all     | check  |  475.00
 all     | all    | 2150.00
(6 rows)

Explanation: Each set in the list is one GROUP BY. (student_id) gives the student totals, (method) the method totals, and () the grand total. ROLLUP and CUBE are shorthand for common sets.

The groupings each clause produces for student_id and method

All three are supported by PostgreSQL, SQL Server and Oracle. MySQL writes GROUP BY student_id, method WITH ROLLUP, and has no CUBE or GROUPING SETS. Tabs showing each database's version are coming to this course.

Common Mistakes

Mistaking a total row for NULL data. Check GROUPING().

Forgetting to sort. Total rows can appear anywhere without ORDER BY.

Using CUBE when ROLLUP is enough. CUBE adds every cross-total, which can be many rows.

Filtering totals with WHERE. WHERE runs before grouping; filter total rows with HAVING GROUPING(col) = 1 or in an outer query.

Interview Corner

What does GROUP BY ROLLUP do?

It computes groupings from most detailed to least, such as (a, b), (a) and (), giving detail rows, subtotals and a grand total in one result.

What's the difference between ROLLUP and CUBE?

ROLLUP (a, b) produces (a, b), (a) and (). CUBE (a, b) produces every combination: (a, b), (a), (b) and ().

What is the GROUPING() function for?

It returns 1 when a column has been aggregated away in a row (a total row), so total rows can be told apart from rows whose value is genuinely NULL.

Practice

Challenge: Show the total paid per month (date_trunc('month', paid_on)::date) with a grand total row at the end, using ROLLUP. Label the total row's month as 'Total' (cast the month to text for the other rows).

Show solution
SQL▶ Try it
SELECT CASE WHEN GROUPING(date_trunc('month', paid_on)) = 1 THEN 'Total'
            ELSE date_trunc('month', paid_on)::date::text END AS month,
       sum(amount_usd) AS total
FROM payments
GROUP BY ROLLUP (date_trunc('month', paid_on))
ORDER BY GROUPING(date_trunc('month', paid_on)), date_trunc('month', paid_on);
Output
   month    |  total
------------+---------
 2025-08-01 |  450.00
 2025-10-01 |  250.00
 2025-11-01 |  225.00
 2025-12-01 | 1025.00
 2026-01-01 |  200.00
 Total      | 2150.00
(6 rows)

Five monthly rows and one total row, $2,150.00. GROUPING() takes the same expression that appears in the ROLLUP.

Quick check: ROLLUP, CUBE and GROUPING SETS

3 questions
1Which groupings does ROLLUP (student_id, method) produce?
2A ROLLUP row shows method NULL and GROUPING(method) = 0. What does it mean?
3What does CUBE add compared with ROLLUP for two columns?

Key Takeaways

You want toWrite
Subtotals and totalGROUP BY ROLLUP (student_id, method)
Every cross-totalGROUP BY CUBE (student_id, method)
Chosen totalsGROUP BY GROUPING SETS ((student_id), (method), ())
Label total rowsCASE WHEN GROUPING(method) = 1 THEN 'All methods' ELSE ... END

Was this tutorial helpful?

Lesson 67 of 115