SQL Practice Logo

SQLPractice Online

ROLLUP & CUBE: Concept

Module: Aggregate Functions & Grouping

ROLLUP and CUBE extend GROUP BY to create subtotals and grand totals automatically, enabling hierarchical and multi-dimensional reporting.

**ROLLUP:**

Creates hierarchical subtotals from right to left.

GROUP BY ROLLUP(region, country, city)

Creates groups for:

- (region, country, city) - detail

- (region, country) - country subtotals

- (region) - region subtotals

- () - grand total

**CUBE:**

Creates all possible combinations (power set).

GROUP BY CUBE(region, product)

Creates groups for:

- (region, product) - detail

- (region) - region totals

- (product) - product totals

- () - grand total

**GROUPING Function:**

Identifies subtotal rows (returns 1 for subtotal, 0 for detail).

GROUPING(region) = 1 means this is a subtotal row where region is NULL.

**Use Cases:**

- ROLLUP: Hierarchical reports (region→country→city)

- CUBE: Multi-dimensional analysis (all combinations)

- GROUPING SETS: Custom combinations

Essential for BI developers and data analysts creating hierarchical reports, financial statements, and multi-dimensional analysis for executives.

Powers executive reports with subtotals and grand totals: sales by region→country→city with totals at each level, revenue by year→quarter→month with period totals.