CUBE for All Combinations
Every grouping combination at once.
What Is CUBE?
The CUBE extension in SQL generates every possible combination of grouping from a list of columns. Where ROLLUP creates a hierarchy, CUBE produces a full cross-product of subtotals — including the grand total.
Think of it as answering: "Give me every subtotal you can compute from these columns."
Setting Up the Table
We will use a sales table that tracks revenue by year, region, and product category. This kind of multi-dimensional data is where CUBE shines.
CREATE TABLE sales (
year INT,
region VARCHAR(20),
category VARCHAR(20),
revenue NUMERIC(10,2)
);
INSERT INTO sales VALUES
(2023, 'North', 'Electronics', 12000),
(2023, 'North', 'Clothing', 8000),
(2023, 'South', 'Electronics', 9500),
(2023, 'South', 'Clothing', 6000),
(2024, 'North', 'Electronics', 14000),
(2024, 'North', 'Clothing', 9500),
(2024, 'South', 'Electronics', 11000),
(2024, 'South', 'Clothing', 7200);All lessons in this course
- Beyond a Single GROUP BY
- ROLLUP for Subtotals
- CUBE for All Combinations
- GROUPING SETS Explained