Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 99/ 160
05. Window Functions & Analytical SQL

GROUPING SETS, ROLLUP & CUBE for Multi-Level Subtotals

Compute multiple grouping levels and subtotals in one scan.

AdvancedGROUPING SETS · ROLLUP3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

One query gives you the detailed totals, the subtotals and the overall total at the same time.

Think of it like…

A sales report printed with a line for each product, a subtotal under each region, and a grand total at the bottom, all from one pass over the receipts.

Where you’ve seen it

SELECT region, product, SUM(revenue) FROM sales GROUP BY ROLLUP (region, product) ORDER BY region, product; returns each (region, product), a subtotal per region (product NULL) and a grand total (both NULL), ready for a report.

Words you’ll hear

GROUPING SETS
An explicit list of groupings to compute in one query.
ROLLUP
Hierarchical subtotals from left to right, plus a grand total.
CUBE
Subtotals for every combination of the listed columns (2ⁿ groupings).
GROUPING(col)
Returns 1 when col is aggregated away in that row, to tell subtotal NULLs from real NULLs.

Visual diagram

Loading interactive diagram

Theory & example queries

GROUPING SETS, ROLLUP and CUBE

GROUPING SETS is the general form: list each grouping you want, and the database computes them all, usually with a single scan, and stacks the results. () is the empty grouping, the grand total. Columns not part of a row's grouping come back as NULL.

ROLLUP(a, b, c) means (a, b, c), (a, b), (a), (): natural for hierarchies like year > month > day or country > state > city. CUBE(a, b, c) means all 2³ = 8 combinations, which suits cross-tab analysis but grows fast. You can mix them: GROUP BY year, ROLLUP (region, product).

Product and region subtotals, independentlyQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  region,3  product,4  SUM(revenue)5FROM6  sales7GROUP BY8  GROUPING SETS ((region), (product), ());
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative grouping-set totals4 sample rows
Representative grouping-set totals
regionproductsum
NorthNULL1200
NULLWidget A700
NULLWidget B500
NULLNULL1200

Note: Sample rows show one region subtotal, two product subtotals and the grand total; NULL marks a rolled-up dimension and additional groups may exist.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

gives totals per region, totals per product, and the grand total, without the detail rows.

Key takeaway: GROUPING SETS lists groupings; ROLLUP = hierarchy; CUBE = every combination.

Telling subtotal NULLs from real NULLs

If region itself can be NULL in the data, a NULL region in the result could be either a real "unknown region" group or a subtotal row. GROUPING(region) returns 1 for rows where region was rolled up and 0 otherwise, so you can label them reliably.

Support varies: PostgreSQL (9.5+), SQL Server, Oracle, Snowflake and BigQuery support all three. MySQL supports only GROUP BY a, b WITH ROLLUP and, since 8.0, the GROUPING() function. Sorting needs care too: ORDER BY GROUPING(region), region places subtotals after their detail rows.

Readable labelsQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  CASE3    WHEN GROUPING(region) = 1 THEN 'All regions'4    ELSE region5  END AS region,6  CASE7    WHEN GROUPING(product) = 1 THEN 'All products'8    ELSE product9  END AS product,10  SUM(revenue)11FROM12  sales13GROUP BY14  ROLLUP (region, product);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/14
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative labelled rollup4 sample rows
Representative labelled rollup
regionproductsum
NorthWidget A700
NorthWidget B500
NorthAll products1200
All regionsAll products1200

Note: Illustrative North-only sales data. ROLLUP also returns detail and subtotal rows for every other region present.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Use GROUPING() for labels; check your database's support.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

List the levels the report needs

Write down each total the report shows: per product within region, per region, overall.

Focus at this step

detail · region subtotal · grand total

What to watch at this step
Levels
3
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

GROUPING SETS computes several GROUP BYs in one query: GROUP BY GROUPING SETS ((region, product), (region), ()) returns per-product rows, per-region subtotals and a grand total. ROLLUP(a, b) is shorthand for the hierarchy (a, b), (a), (). CUBE(a, b) gives every combination: (a, b), (a), (b), (). Subtotal rows show NULL in the columns that were rolled up.

Why it matters: Finance and sales reports need detail lines, subtotals and a grand total together. Writing several queries and UNIONing them means several scans and messy code; ROLLUP does it in one. It's an advanced SQL interview topic, often paired with the GROUPING() function question.

When to reach for it

  • Financial and sales reports with subtotals
  • Feeding pivot-style dashboards with all totals at once
  • Replacing UNION ALL of several GROUP BY queries

When to avoid or be careful

  • CUBE over many columns (the number of groupings doubles with each one)
  • Reading NULL as a subtotal when the data itself contains NULLs
  • Expecting GROUPING SETS or CUBE in MySQL

ROLLUP vs CUBE vs UNION ALL of GROUP BYs

ROLLUP
Best for: Hierarchical subtotals (year > month, region > product)

Strengths: Short, one scan, natural report shape.

Watch out: Order of columns defines the hierarchy.

CUBE / GROUPING SETS
Best for: Cross-tab totals or a custom set of groupings

Strengths: Every needed combination in one query.

Watch out: CUBE grows exponentially; not available in MySQL.

UNION ALL of separate GROUP BYs
Best for: Databases without grouping sets

Strengths: Works everywhere and is easy to follow.

Watch out: Scans the data once per level; repetitive code.

Interview signals & numbers to know

When this topic comes up

  • “Show subtotals and a grand total”
  • “Totals by region, by product and overall”
  • “What does ROLLUP do?”
  • GROUPING() function
  • Financial reporting

Benchmarks & rules of thumb

n + 1 -
groupings produced by ROLLUP of n columns
2ⁿ -
groupings produced by CUBE of n columns
1 -
scan of the table, typically

Common mistakes & follow-ups

Common interview mistakes

  • Treating every NULL in the result as a subtotal when the column has real NULLs.
  • Using CUBE when only hierarchical subtotals were needed, producing confusing extra rows.
  • Writing three GROUP BY queries with UNION ALL when one ROLLUP would do.

Likely interviewer follow-ups

  • What's the difference between ROLLUP and CUBE?
  • How do you tell a subtotal row from a row with a real NULL value?
  • How many groupings does ROLLUP(year, month, day) produce?
Interview tip: Show ROLLUP on two columns and list the three groupings it creates, then mention GROUPING() for labels. It's compact and covers the usual follow-up.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply GROUPING SETS, ROLLUP & CUBE for Multi-Level Subtotals with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
FILTER (WHERE ...) Clause with Aggregates & Window Functions
Next topic
Solving Classic FAANG / Senior Data Analyst SQL Interview Problems