Skip to content
/ Chapter 16 · Summary Reports and Pivots
Lesson 16.5 · garden_shop
Lesson 16.5

GROUPING SETS and CUBE in SQL

GROUPING SETS lists several GROUP BY levels in one query; CUBE returns every combination of them.

ROLLUP builds a hierarchy of subtotals: category, then category plus supplier, then a grand total. But sometimes you want totals for two dimensions independently: a breakdown by category and a separate breakdown by supplier without the nested combinations.

GROUPING SETS gives you exactly that control: you list each grouping level you want, and the empty set () adds the grand total. CUBE is the shortcut for "every combination of these dimensions".

Pattern
select region, product, sum(amount) as total
from sales
group by grouping sets ((region), (product), ())
-- ROLLUP(region, product) = a hierarchy of subtotals
-- CUBE(region, product)   = every combination of subtotals

Labeling the subtotal rows

On a per-supplier subtotal row there is no single category, so category_name comes back as NULL. If source data can also contain real nulls, coalesce() alone cannot tell them apart. Use grouping() to identify generated subtotal rows before assigning labels such as "All categories".

Schema · Garden Shop Tables · products, categories, suppliers 3 tables
Table · products

One row per product, with price, cost, and inventory levels.

9 columns · 24 rows
product_id int product_name text category_id int supplier_id int price decimal cost decimal quantity_on_hand int reorder_level int discontinued bool
Table · categories

Lookup table of product categories.

2 columns · 8 rows
category_id int category_name text
Table · suppliers

One row per supplier. Some suppliers have no contact email.

4 columns · 6 rows
supplier_id int supplier_name text contact_email text state text
Your task

In one query, count products by category, by supplier, and overall. Label the subtotal rows "All categories" and "All suppliers" so every row reads clearly, and sort by category, then supplier.

·

Run your query to inspect the result.

Expected answer
  • Columns: category, supplier, product_count.
  • Eight per-category rows, five per-supplier rows, and one grand-total row (14 rows).
  • ROLLUP is a hierarchy; GROUPING SETS lets you pick independent levels, and CUBE returns every combination.