🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Analytical SQL: Pivoting, Unpivoting, Grouping Sets, Cube

Advanced SQLAnalytical Patterns⭐ Premium

Interview Question: "Explain the difference between ROLLUP and CUBE. How do you pivot rows to columns without a CASE statement? What are GROUPING SETS and when would you use them?" — Asked at Tableau, Looker, Databricks for Analytics Engineer roles

â„šī¸

Difficulty: Advanced | Companies: Tableau, Looker, Databricks, Snowflake, Google BigQuery | Time: 45-60 minutes

GROUPING SETS Fundamentals

Most reporting requests arrive as "show me totals at more than one level in the same result set". The naive approach runs several GROUP BY queries and stitches the results together in the application, which multiplies scans over the fact table and lets the numbers drift out of sync if data changes between runs. GROUPING SETS evaluates every subtotal level in a single pass: the database scans the base rows once and emits one output row per grouping set per matching combination. Cost grows with the number of sets you declare, not with the number of separate queries you would otherwise issue.

-- Create sales data for analysis
CREATE TABLE regional_sales (
    year INT,
    quarter INT,
    region VARCHAR(50),
    product_category VARCHAR(50),
    sales_amount DECIMAL(12,2),
    quantity INT
);

INSERT INTO regional_sales VALUES
(2023, 1, 'North', 'Electronics', 150000.00, 1200),
(2023, 1, 'North', 'Clothing', 80000.00, 2400),
(2023, 1, 'South', 'Electronics', 120000.00, 960),
(2023, 1, 'South', 'Clothing', 95000.00, 2850),
(2023, 2, 'North', 'Electronics', 165000.00, 1320),
(2023, 2, 'North', 'Clothing', 75000.00, 2250),
(2023, 2, 'South', 'Electronics', 135000.00, 1080),
(2023, 2, 'South', 'Clothing', 88000.00, 2640),
(2024, 1, 'North', 'Electronics', 180000.00, 1440),
(2024, 1, 'North', 'Clothing', 85000.00, 2550),
(2024, 1, 'South', 'Electronics', 145000.00, 1160),
(2024, 1, 'South', 'Clothing', 92000.00, 2760);

-- GROUPING SETS: Multiple aggregations in one query
SELECT 
    year,
    region,
    product_category,
    SUM(sales_amount) AS total_sales,
    SUM(quantity) AS total_qty,
    GROUPING(year) AS is_year_agg,
    GROUPING(region) AS is_region_agg,
    GROUPING(product_category) AS is_category_agg
FROM regional_sales
GROUP BY GROUPING SETS (
    (year, region, product_category),  -- Detail level
    (year, region),                    -- Region subtotals
    (year),                            -- Year totals
    ()                                 -- Grand total
)
ORDER BY year, region, product_category;

Output:

yearregionproduct_categorytotal_salestotal_qtyis_year_aggis_region_aggis_category_agg
2023NorthClothing155000.004650000
2023NorthElectronics315000.002520000
2023North*470000.007170001
2023SouthClothing183000.005490000
2023SouthElectronics255000.002040000
2023South*438000.007530001
2023**908000.0014700011
2024NorthClothing85000.002550000
2024NorthElectronics180000.001440000
2024North*265000.003990001
2024SouthClothing92000.002760000
2024SouthElectronics145000.001160000
2024South*237000.003920001
2024**502000.007910011
***1410000.0022610111

â„šī¸

GROUPING Function: Returns 1 if column is aggregated (NULL from grouping), 0 if column is part of the GROUP BY.

Reading the output table: a * in a column means that column was rolled up for that row, and the matching is_*_agg flag is 1. Detail rows carry all zeros; the grand-total row carries all ones. Downstream report layers usually replace the * placeholders with labels such as "All categories" and use GROUPING(product_category) = 1 in a HAVING clause when they only want the subtotal rows.

Choosing Between GROUPING SETS, ROLLUP, and CUBE

Pick the operator by the shape of the subtotal hierarchy you need:

NeedOperatorSets produced for (year, quarter, region)
Exact, irregular list of levelsGROUPING SETSOnly the sets you enumerate
Nested calendar-style rollupROLLUP(year, quarter, region), (year, quarter), (year), ()
Every combination, including single dimensionsCUBEAll 2^n sets: 8 for three columns

ROLLUP assumes each column hierarchically contains the next: year contains quarter, quarter contains region. Grouping by (region, product_category) with ROLLUP yields (region, category), (region) and () — never category alone. CUBE removes that assumption: for n columns it emits 2^n grouping sets, so (year, quarter, region) produces 8 sets instead of 4. That is exactly what you want when analysts ask for "totals by quarter across all regions", but the row count explodes quickly — six grouping columns already generate 64 sets.

Decision rule: start with ROLLUP whenever dimensions form a clear hierarchy (time, geography, org chart). Reach for CUBE only when single-dimension marginal totals are an explicit requirement. Hand-write GROUPING SETS when the levels are irregular, for example detail rows plus a year total plus a grand total but no region subtotal.

GROUPING_ID and Deterministic Subtotal Sorting

With mixed aggregation levels in one result, a plain ORDER BY year, region interleaves detail rows and subtotals in a way that is unreadable in a table grid. GROUPING_ID(year, region, product_category) returns a bitmask you can sort by: each aggregated column contributes one bit, so detail rows score 0 and the grand total scores 7 for three columns.

-- Sort detail rows first, then coarser subtotals, then the grand total
SELECT
    year,
    region,
    product_category,
    SUM(sales_amount) AS total_sales,
    GROUPING_ID(year, region, product_category) AS gid
FROM regional_sales
GROUP BY GROUPING SETS (
    (year, region, product_category),
    (year, region),
    (year),
    ()
)
ORDER BY year, gid, region NULLS LAST, product_category NULLS LAST;

Reporting tools use the gid column to indent or shade subtotal rows instead of guessing aggregation level from NULL values, which breaks as soon as a real measure can also be NULL.

ROLLUP vs CUBE

-- ROLLUP: Hierarchical subtotals
SELECT 
    year,
    quarter,
    region,
    SUM(sales_amount) AS total_sales
FROM regional_sales
GROUP BY ROLLUP(year, quarter, region)
ORDER BY year, quarter, region;

-- CUBE: All possible combinations
SELECT 
    year,
    quarter,
    region,
    SUM(sales_amount) AS total_sales
FROM regional_sales
GROUP BY CUBE(year, quarter, region)
ORDER BY year, quarter, region;

ROLLUP Output:

yearquarterregiontotal_sales
20231North230000.00
20231South215000.00
20231*445000.00
20232North240000.00
20232South223000.00
20232*463000.00
2023**908000.00
20241North265000.00
20241South237000.00
20241*502000.00
2024**502000.00
***1410000.00

Pivoting Rows to Columns

Conditional aggregation (the CASE form) is the portable pivot: it works on every SQL engine, and the column list is visible in the query text, which keeps review and refactor simple. The trade-off is that adding a region means editing the SELECT list by hand. PostgreSQL's crosstab() from the tablefunc extension avoids hand-written CASE, but the second argument fixes the output column order, so new region values do not appear until you change the query.

-- Static pivot using conditional aggregation
SELECT 
    year,
    SUM(CASE WHEN region = 'North' THEN sales_amount ELSE 0 END) AS north_sales,
    SUM(CASE WHEN region = 'South' THEN sales_amount ELSE 0 END) AS south_sales,
    SUM(CASE WHEN region = 'East' THEN sales_amount ELSE 0 END) AS east_sales,
    SUM(CASE WHEN region = 'West' THEN sales_amount ELSE 0 END) AS west_sales,
    SUM(sales_amount) AS total_sales
FROM regional_sales
WHERE year = 2024
GROUP BY year;

-- Pivot using crosstab (requires tablefunc extension)
CREATE EXTENSION IF NOT EXISTS tablefunc;

SELECT * FROM crosstab(
    'SELECT year, region, SUM(sales_amount)::INT 
     FROM regional_sales 
     GROUP BY year, region 
     ORDER BY year, region',
    'SELECT DISTINCT region FROM regional_sales ORDER BY region'
) AS ct(year INT, east INT, north INT, south INT, west INT);

Pivot Output:

yeareast_salesnorth_salessouth_saleswest_salestotal_sales
20230470000.00438000.000908000.00
20240265000.00237000.000502000.00

Two details bite in production. First, cells with no matching source rows come back as NULL under the CASE form unless you coalesce them — the ELSE 0 branch above is deliberate, because a NULL quarter and a zero quarter drive different chart renderings. Second, the set of pivot values is frozen at query-design time: when a new region appears in the data it silently disappears from the report unless someone edits the SELECT list. That is the problem dynamic pivots solve.

Unpivoting Columns to Rows

The three unpivot strategies differ in scan count and NULL behaviour. UNION ALL scans the wide table once per column you unpivot — four regions means four scans — but it works everywhere and each branch can be renamed or filtered independently. CROSS JOIN LATERAL over a VALUES list scans the source once and expands each row into k result rows in memory; planners usually choose this shape on wide tables. SQL Server's native UNPIVOT drops rows whose value column is NULL, which silently hides missing data — if you need to keep empty quarters as zeros, coalesce before unpivoting or filter explicitly.

-- Create pivoted table
CREATE TABLE yearly_sales (
    year INT,
    north_sales DECIMAL(12,2),
    south_sales DECIMAL(12,2),
    east_sales DECIMAL(12,2),
    west_sales DECIMAL(12,2)
);

INSERT INTO yearly_sales VALUES
(2023, 470000.00, 438000.00, 0, 0),
(2024, 265000.00, 237000.00, 0, 0);

-- Unpivot using UNION ALL
SELECT year, 'North' AS region, north_sales AS sales_amount
FROM yearly_sales
UNION ALL
SELECT year, 'South' AS region, south_sales AS sales_amount
FROM yearly_sales
UNION ALL
SELECT year, 'East' AS region, east_sales AS sales_amount
FROM yearly_sales
UNION ALL
SELECT year, 'West' AS region, west_sales AS sales_amount
FROM yearly_sales
ORDER BY year, region;

-- Unpivot using LATERAL JOIN
SELECT 
    y.year,
    r.region,
    r.sales_amount
FROM yearly_sales y
CROSS JOIN LATERAL (
    VALUES 
        ('North', y.north_sales),
        ('South', y.south_sales),
        ('East', y.east_sales),
        ('West', y.west_sales)
) AS r(region, sales_amount)
ORDER BY y.year, r.region;

Unpivot Output:

yearregionsales_amount
2023East0
2023North470000.00
2023South438000.00
2023West0
2024East0
2024North265000.00
2024South237000.00
2024West0

âš ī¸

Performance: Unpivoting with UNION ALL creates multiple scans. For large datasets, consider using LATERAL JOIN or stored procedures.

Dynamic Pivot with EXECUTE

The DO block below builds the column list at run time: it collects the distinct regions, formats one SUM(CASE ...) expression per region, then executes the finished string. Three production details matter. Identifier quoting — region names with spaces or mixed case must go through format's %I placeholder or the generated SQL breaks. Plan caching — dynamic SQL executes as fresh text, so it bypasses prepared-statement caches; on large tables this shows up as repeated parse cost on every run. Debuggability — log the generated string with RAISE NOTICE before trusting the numbers, because a malformed column alias fails only at EXECUTE time.

-- Dynamic pivot for unknown number of columns
DO $$
DECLARE
    sql TEXT;
    regions TEXT;
BEGIN
    -- Get distinct regions
    SELECT STRING_AGG(DISTINCT region, ', ' ORDER BY region) INTO regions
    FROM regional_sales;
    
    -- Build dynamic query
    sql := 'SELECT year, ';
    sql := sql || STRING_AGG(
        format('SUM(CASE WHEN region = %L THEN sales_amount ELSE 0 END) AS %I_sales', 
               region, LOWER(region)),
        ', '
    );
    sql := sql || ' FROM regional_sales GROUP BY year ORDER BY year';
    
    -- Execute and return results
    RAISE NOTICE '%', sql;
    EXECUTE sql;
END $$;

Window Functions with GROUPING SETS

Window functions run after grouping, so you can rank the subtotal rows themselves: the CTE below produces detail rows, region subtotals, year totals and the grand total in one set, then computes each row's share of its year. Because the year total also appears as its own row, divide carefully — either filter region IS NOT NULL before computing percentages, or accept that the subtotal row shows 100 percent of itself.

-- Combine window functions with GROUPING SETS
WITH regional_totals AS (
    SELECT 
        year,
        region,
        SUM(sales_amount) AS total_sales
    FROM regional_sales
    GROUP BY GROUPING SETS ((year, region), (year), ())
)
SELECT 
    year,
    region,
    total_sales,
    -- Rank within year
    RANK() OVER (
        PARTITION BY year 
        ORDER BY total_sales DESC
    ) AS rank_in_year,
    -- Percentage of year total
    ROUND(
        total_sales * 100.0 / 
        SUM(total_sales) OVER (PARTITION BY year),
        2
    ) AS pct_of_year,
    -- Running total
    SUM(total_sales) OVER (
        ORDER BY year, region
        ROWS UNBOUNDED PRECEDING
    ) AS running_total
FROM regional_totals
ORDER BY year, region NULLS LAST;

Mathematical Properties

For GROUPING SETS with columns:

The aggregation level hierarchy:

Advanced: LISTAGG and String Aggregation

-- Aggregate strings with LISTAGG
SELECT 
    year,
    region,
    LISTAGG(DISTINCT product_category, ', ') WITHIN GROUP (ORDER BY product_category) AS categories,
    STRING_AGG(DISTINCT product_category, ' | ' ORDER BY product_category) AS categories_alt
FROM regional_sales
GROUP BY year, region
ORDER BY year, region;

Output:

yearregioncategoriescategories_alt
2023NorthClothing, ElectronicsClothing | Electronics
2023SouthClothing, ElectronicsClothing | Electronics
2024NorthClothing, ElectronicsClothing | Electronics
2024SouthClothing, ElectronicsClothing | Electronics

â„šī¸

LISTAGG vs STRING_AGG: LISTAGG is SQL standard, STRING_AGG is PostgreSQL-specific. Both support DISTINCT, ORDER BY, and separators.

Pivot with Aggregation Functions

Pivoting rarely stops at SUM. Counting transactions alongside total and average sale separates "one whale order" from "many small orders", and standard deviation flags quarters where sales were volatile even when the average looks healthy. All of these compose in the same conditional pattern — one column per (region, metric) combination.

-- Pivot with multiple aggregation functions
SELECT 
    year,
    region,
    COUNT(*) AS transaction_count,
    SUM(sales_amount) AS total_sales,
    AVG(sales_amount) AS avg_sale,
    MAX(sales_amount) AS max_sale,
    MIN(sales_amount) AS min_sale,
    STDDEV(sales_amount) AS stddev_sale
FROM regional_sales
GROUP BY year, region
ORDER BY year, region;

Performance Considerations

All the grouping-set variants share the same engine shape: sort (or hash) the input, then aggregate once per set. The differentiator is set count. ROLLUP on n columns costs n + 1 sets, CUBE costs 2^n, and an explicit GROUPING SETS list costs exactly what you wrote. Pivoting via CASE aggregation is linear in input rows; UNION ALL unpivoting multiplies rows by the number of columns you explode.

OperationTime ComplexitySpace ComplexityNotes
GROUPING SETSSort + aggregate
ROLLUPHierarchical
CUBEAll combinations
PIVOTConditional
UNPIVOTUNION ALL

Before shipping a CUBE query on more than four or five dimensions, run EXPLAIN on a realistic slice: the grouping-set explosion shows up as a bloated HashAggregate or a long sort, and the fix is usually to replace CUBE with the two or three GROUPING SETS the report actually renders.

âš ī¸

Memory Warning: CUBE with many columns generates exponential grouping sets. Monitor memory usage with EXPLAIN ANALYZE.

When (Not) to Use These Patterns

Use GROUPING SETS, ROLLUP or CUBE when a single query must return several aggregation levels for a dashboard or export. Skip them when the application only ever displays one level at a time — separate indexed GROUP BY queries are cheaper, cacheable, and easier to reason about. Also skip dynamic pivots when the column set is stable: a static CASE pivot is auditable in code review, while a string-built query is not. A practical middle ground is to generate the dynamic pivot during ETL, persist the wide table, and let serving queries stay static.

Common Mistakes

Using CUBE on six or more dimensions and being surprised by 64-plus grouping sets

Fix: Enumerate only the GROUPING SETS the report needs, or keep ROLLUP for hierarchical dimensions

Inferring aggregation level from NULL values in the output

Fix: Use GROUPING(col) or GROUPING_ID(...) flags — a real measure can legitimately be NULL

Writing a dynamic pivot whose column identifiers come straight from data

Fix: Quote with format's %I, validate the generated SQL via RAISE NOTICE, and consider persisting the wide table instead

Assuming native UNPIVOT keeps NULL-valued cells

Fix: Coalesce values before unpivoting, or switch to UNION ALL / LATERAL so empty cells stay visible

Key Takeaways

  • GROUPING SETS evaluates every subtotal level in one scan; ROLLUP assumes a hierarchy, CUBE emits all 2^n combinations
  • GROUPING(col) and GROUPING_ID(...) mark which columns were aggregated — sort and filter on those flags instead of guessing from NULLs
  • CASE-based pivots are the portable default; dynamic SQL pivots are the escape hatch when column values are only known at run time
  • UNION ALL unpivots everywhere but scans once per column; LATERAL over VALUES scans once and expands rows in memory
🔒

Premium Content

Analytical SQL: Pivoting, Unpivoting, Grouping Sets, Cube

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-15

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement