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

Dynamic PIVOT/UNPIVOT: Crosstab Reports, Matrix Queries

Advanced SQLPIVOT/UNPIVOT⭐ Premium

Interview Question: "How do you create a dynamic pivot table when the number of columns is unknown at compile time? Explain the performance implications of pivoting large datasets." — Asked at Tableau, Looker, PowerBI for Analytics Engineer roles

â„šī¸

Difficulty: Advanced | Companies: Tableau, Looker, PowerBI, Qlik, Sisense | Time: 45-60 minutes

Static PIVOT with CASE

Rotating rows into columns is a projection change, not an access-path change. The engine still reads every row of monthly_sales, applies the aggregation, then emits one column per branch of the CASE. Two numbers decide whether this is affordable: how many rows you scan, and how many branches you emit. Each branch adds a conditional aggregate to the plan, so a 12-month by 8-region crosstab runs eight aggregates per group instead of one. The query below hard-codes four regions; when a fifth region appears in tomorrow's data it lands in no column at all, and the sum of the regional columns quietly stops matching total_revenue. Emitting SUM(revenue) alongside the branches puts that mismatch in the same row where a reader can see it.

-- Create sales data
CREATE TABLE monthly_sales (
    year INT,
    month INT,
    region VARCHAR(20),
    product VARCHAR(50),
    revenue DECIMAL(12,2)
);

INSERT INTO monthly_sales VALUES
(2024, 1, 'North', 'Laptop', 150000),
(2024, 1, 'North', 'Phone', 200000),
(2024, 1, 'South', 'Laptop', 120000),
(2024, 1, 'South', 'Phone', 180000),
(2024, 2, 'North', 'Laptop', 160000),
(2024, 2, 'North', 'Phone', 210000),
(2024, 2, 'South', 'Laptop', 130000),
(2024, 2, 'South', 'Phone', 190000),
(2024, 3, 'North', 'Laptop', 170000),
(2024, 3, 'North', 'Phone', 220000),
(2024, 3, 'South', 'Laptop', 140000),
(2024, 3, 'South', 'Phone', 200000);

-- Static pivot: rows to columns
SELECT 
    year,
    month,
    SUM(CASE WHEN region = 'North' THEN revenue ELSE 0 END) AS north_revenue,
    SUM(CASE WHEN region = 'South' THEN revenue ELSE 0 END) AS south_revenue,
    SUM(CASE WHEN region = 'East' THEN revenue ELSE 0 END) AS east_revenue,
    SUM(CASE WHEN region = 'West' THEN revenue ELSE 0 END) AS west_revenue,
    SUM(revenue) AS total_revenue
FROM monthly_sales
GROUP BY year, month
ORDER BY year, month;

Output:

yearmonthnorth_revenuesouth_revenueeast_revenuewest_revenuetotal_revenue
2024135000030000000650000
2024237000032000000690000
2024339000034000000730000

Sizing the Matrix Before You Build It

A crosstab trades rows for columns, and the exchange rate is the cardinality of the pivot key. Take daily sales for 500 products across one year: that is 500 × 365 = 182,500 rows in long form. Pivot by month and you get 500 × 12 = 6,000 cells; pivot by ISO week and 500 × 53 ≈ 26,500 cells; pivot by customer and, with 40,000 customers, you get 7.3 million cells — that is not a report, it is a denial of service against your spreadsheet. The practical ceiling is a few hundred columns: most BI tools render 30 to 60 columns legibly, and PostgreSQL's crosstab forces you to declare every column in the AS clause, so the shape must be known before the query runs.

Pivot key cardinalityLong rowsWide cellsVerdict
12 months182,5006,000Comfortable
53 ISO weeks182,50026,500Wide but usable
365 days182,500182,500Keep the data long
40,000 customers182,5007,300,000Never

An unbounded key — customer, product, session — should stay long and be pivoted only at the presentation layer, where the filter and top-N are applied first.

crosstab Function (tablefunc)

-- Enable tablefunc extension
CREATE EXTENSION IF NOT EXISTS tablefunc;

-- Basic crosstab
SELECT * FROM crosstab(
    'SELECT year, month, SUM(revenue)::INT 
     FROM monthly_sales 
     GROUP BY year, month 
     ORDER BY year, month',
    'SELECT DISTINCT month FROM monthly_sales ORDER BY month'
) AS ct(year INT, jan INT, feb INT, mar INT);

-- crosstab with multiple value columns
SELECT * FROM crosstab(
    'SELECT year, region, SUM(revenue)::INT 
     FROM monthly_sales 
     GROUP BY year, region 
     ORDER BY year, region',
    'SELECT DISTINCT region FROM monthly_sales ORDER BY region'
) AS ct(year INT, north INT, south INT);

Output:

yearjanfebmar
2024650000690000730000

Dynamic PIVOT with EXECUTE

Dynamic SQL is the only technique that lets the data decide the shape of the result. The block below reads the distinct regions, builds one conditional aggregate per region, then executes the assembled statement. Two costs come with that flexibility. First, the statement text does not exist until run time, so the planner cannot prepare it in advance and every distinct region set pays one to three milliseconds of extra planning. Second, the column list is derived from data, so any region value becomes part of a statement — build labels with format('%I', region) and values with format('%L', region) so quotes and reserved words cannot break the text. The example prints the statement through RAISE NOTICE before executing it, which is the cheapest audit log you can have while you are debugging a generated query.

-- Dynamic pivot for unknown columns
DO $$
DECLARE
    sql TEXT;
    col_list TEXT;
    regions TEXT[];
BEGIN
    -- Get distinct regions
    SELECT ARRAY_AGG(DISTINCT region ORDER BY region) INTO regions
    FROM monthly_sales;
    
    -- Build column list
    SELECT STRING_AGG(
        format('SUM(CASE WHEN region = %L THEN revenue ELSE 0 END) AS %I', 
               region, LOWER(region)),
        ', '
    ) INTO col_list
    FROM unnest(regions) AS region;
    
    -- Build full query
    sql := format('
        SELECT 
            year,
            month,
            %s,
            SUM(revenue) AS total_revenue
        FROM monthly_sales
        GROUP BY year, month
        ORDER BY year, month',
        col_list
    );
    
    -- Execute and return results
    RAISE NOTICE '%', sql;
    EXECUTE sql;
END $$;

UNPIVOT with UNION ALL

-- Create pivoted table
CREATE TABLE pivoted_sales (
    year INT,
    north_revenue DECIMAL(12,2),
    south_revenue DECIMAL(12,2),
    east_revenue DECIMAL(12,2),
    west_revenue DECIMAL(12,2)
);

INSERT INTO pivoted_sales VALUES
(2024, 350000, 300000, 0, 0),
(2024, 370000, 320000, 0, 0),
(2024, 390000, 340000, 0, 0);

-- Unpivot with UNION ALL
SELECT year, 'North' AS region, north_revenue AS revenue
FROM pivoted_sales
UNION ALL
SELECT year, 'South' AS region, south_revenue AS revenue
FROM pivoted_sales
UNION ALL
SELECT year, 'East' AS region, east_revenue AS revenue
FROM pivoted_sales
UNION ALL
SELECT year, 'West' AS region, west_revenue AS revenue
FROM pivoted_sales
ORDER BY year, region;

-- Unpivot with LATERAL JOIN (more efficient)
SELECT 
    p.year,
    r.region,
    r.revenue
FROM pivoted_sales p
CROSS JOIN LATERAL (
    VALUES 
        ('North', p.north_revenue),
        ('South', p.south_revenue),
        ('East', p.east_revenue),
        ('West', p.west_revenue)
) AS r(region, revenue)
WHERE r.revenue > 0
ORDER BY p.year, r.region;

Dynamic UNPIVOT

-- Dynamic unpivot using hstore
CREATE EXTENSION IF NOT EXISTS hstore;

SELECT 
    year,
    (each(hstore(p) - ARRAY['year']::text[])).key AS region,
    (each(hstore(p) - ARRAY['year']::text[])).value::decimal AS revenue
FROM pivoted_sales p
ORDER BY year, region;

-- Alternative: Using jsonb
SELECT 
    year,
    key AS region,
    value::decimal AS revenue
FROM pivoted_sales,
LATERAL jsonb_each_text(to_jsonb(pivoted_sales) - 'year') AS j(key, value)
WHERE value::decimal > 0
ORDER BY year, key;

Nulls, Zeroes and Column Ordering

The two unpivot forms fail at the edges in different ways. SQL Server's UNPIVOT operator discards rows where the source column is NULL, so a region with no sales silently vanishes instead of appearing with a zero; the UNION ALL form shown above has no such restriction, but you have to name every column by hand, which is exactly the maintenance dynamic SQL was meant to remove. Ordering is the other trap: STRING_AGG(DISTINCT region ORDER BY region) emits columns alphabetically, so east leads and west trails, and the layout changes the moment a new region is inserted. Carry an integer ordinal from a dictionary table and sort the generated list by it. Also cast the pivot value deliberately — hstore and jsonb_each_text return text, so revenue comes back as a string and arithmetic on it will fail or compare lexicographically.

💡Make ordering explicit

Attach the sort ordinal to the generated column list rather than relying on alphabetical order. It is stable until a new key value arrives, and then every dashboard reorders without warning.

Matrix Query Pattern

-- Create student grades table
CREATE TABLE student_grades (
    student_id INT,
    subject VARCHAR(50),
    grade DECIMAL(5,2)
);

INSERT INTO student_grades VALUES
(1, 'Math', 95.5),
(1, 'Science', 88.0),
(1, 'English', 92.0),
(2, 'Math', 85.0),
(2, 'Science', 90.5),
(2, 'English', 88.5),
(3, 'Math', 92.0),
(3, 'Science', 95.0),
(3, 'English', 91.0);

-- Matrix: students as rows, subjects as columns
SELECT 
    s.student_name,
    MAX(CASE WHEN sg.subject = 'Math' THEN sg.grade END) AS math,
    MAX(CASE WHEN sg.subject = 'Science' THEN sg.grade END) AS science,
    MAX(CASE WHEN sg.subject = 'English' THEN sg.grade END) AS english,
    ROUND(AVG(sg.grade), 2) AS average
FROM students s
JOIN student_grades sg ON s.student_id = sg.student_id
GROUP BY s.student_id, s.student_name
ORDER BY s.student_name;

Output:

student_namemathscienceenglishaverage
Alice95.5088.0092.0091.83
Bob85.0090.5088.5088.00
Charlie92.0095.0091.0092.67

Pivot with Multiple Aggregations

-- Pivot with SUM, AVG, COUNT
SELECT 
    year,
    month,
    SUM(CASE WHEN region = 'North' THEN revenue ELSE 0 END) AS north_total,
    ROUND(AVG(CASE WHEN region = 'North' THEN revenue END), 2) AS north_avg,
    COUNT(CASE WHEN region = 'North' THEN 1 END) AS north_count,
    SUM(CASE WHEN region = 'South' THEN revenue ELSE 0 END) AS south_total,
    ROUND(AVG(CASE WHEN region = 'South' THEN revenue END), 2) AS south_avg,
    COUNT(CASE WHEN region = 'South' THEN 1 END) AS south_count
FROM monthly_sales
GROUP BY year, month
ORDER BY year, month;

Percent-of-Total Crosstab

Once the matrix exists, the frequent follow-up is "share of row". Compute it after the pivot with an empty OVER () window so the denominator is the row total rather than the branch: dividing north by north + south gives a two-region share, while dividing by SUM(north + south) OVER () gives the correct grand-total share across every row in the result. The same pattern produces contribution to the column total when you add PARTITION BY region, which is the number a regional manager actually asks for.

-- Share of row and share of column after pivoting
WITH pivoted AS (
    SELECT
        year,
        month,
        SUM(CASE WHEN region = 'North' THEN revenue ELSE 0 END) AS north,
        SUM(CASE WHEN region = 'South' THEN revenue ELSE 0 END) AS south,
        SUM(revenue) AS total
    FROM monthly_sales
    GROUP BY year, month
)
SELECT
    year,
    month,
    total,
    ROUND(north * 100.0 / NULLIF(total, 0), 1) AS north_pct,
    ROUND(south * 100.0 / NULLIF(total, 0), 1) AS south_pct,
    ROUND(total * 100.0 / SUM(total) OVER (), 2) AS pct_of_grand_total
FROM pivoted
ORDER BY year, month;

Mathematical Properties

Pivot transformation:

Unpivot transformation:

Matrix representation:

â„šī¸

Performance Tip: Pivot operations require full table scans. For large datasets, pre-aggregate data before pivoting.

Pivot with Window Functions

-- Pivot with ranking
WITH pivoted AS (
    SELECT 
        year,
        month,
        SUM(CASE WHEN region = 'North' THEN revenue ELSE 0 END) AS north,
        SUM(CASE WHEN region = 'South' THEN revenue ELSE 0 END) AS south
    FROM monthly_sales
    GROUP BY year, month
)
SELECT 
    year,
    month,
    north,
    south,
    RANK() OVER (ORDER BY north DESC) AS north_rank,
    RANK() OVER (ORDER BY south DESC) AS south_ratio,
    north::decimal / NULLIF(south, 0) AS north_south_ratio
FROM pivoted
ORDER BY year, month;

Cross-Tabulation Analysis

-- Contingency table for chi-square test
WITH contingency AS (
    SELECT 
        region,
        product,
        COUNT(*) AS frequency
    FROM monthly_sales
    GROUP BY region, product
)
SELECT 
    region,
    SUM(CASE WHEN product = 'Laptop' THEN frequency ELSE 0 END) AS laptop,
    SUM(CASE WHEN product = 'Phone' THEN frequency ELSE 0 END) AS phone,
    SUM(frequency) AS total
FROM contingency
GROUP BY region
ORDER BY region;

-- Expected frequencies for chi-square
WITH observed AS (
    SELECT 
        region,
        product,
        COUNT(*) AS observed
    FROM monthly_sales
    GROUP BY region, product
),
totals AS (
    SELECT 
        SUM(observed) AS grand_total,
        SUM(CASE WHEN product = 'Laptop' THEN observed ELSE 0 END) AS laptop_total,
        SUM(CASE WHEN product = 'Phone' THEN observed ELSE 0 END) AS phone_total,
        SUM(CASE WHEN region = 'North' THEN observed ELSE 0 END) AS north_total,
        SUM(CASE WHEN region = 'South' THEN observed ELSE 0 END) AS south_total
    FROM observed
)
SELECT 
    o.region,
    o.product,
    o.observed,
    ROUND(
        CASE 
            WHEN o.region = 'North' AND o.product = 'Laptop' 
                THEN t.north_total * t.laptop_total::decimal / t.grand_total
            WHEN o.region = 'North' AND o.product = 'Phone' 
                THEN t.north_total * t.phone_total::decimal / t.grand_total
            WHEN o.region = 'South' AND o.product = 'Laptop' 
                THEN t.south_total * t.laptop_total::decimal / t.grand_total
            WHEN o.region = 'South' AND o.product = 'Phone' 
                THEN t.south_total * t.phone_total::decimal / t.grand_total
        END, 2
    ) AS expected,
    ROUND(
        POWER(o.observed - 
            CASE 
                WHEN o.region = 'North' AND o.product = 'Laptop' 
                    THEN t.north_total * t.laptop_total::decimal / t.grand_total
                WHEN o.region = 'North' AND o.product = 'Phone' 
                    THEN t.north_total * t.phone_total::decimal / t.grand_total
                WHEN o.region = 'South' AND o.product = 'Laptop' 
                    THEN t.south_total * t.laptop_total::decimal / t.grand_total
                WHEN o.region = 'South' AND o.product = 'Phone' 
                    THEN t.south_total * t.phone_total::decimal / t.grand_total
            END, 2) / 
            CASE 
                WHEN o.region = 'North' AND o.product = 'Laptop' 
                    THEN t.north_total * t.laptop_total::decimal / t.grand_total
                WHEN o.region = 'North' AND o.product = 'Phone' 
                    THEN t.north_total * t.phone_total::decimal / t.grand_total
                WHEN o.region = 'South' AND o.product = 'Laptop' 
                    THEN t.south_total * t.laptop_total::decimal / t.grand_total
                WHEN o.region = 'South' AND o.product = 'Phone' 
                    THEN t.south_total * t.phone_total::decimal / t.grand_total
            END, 2
    ) AS chi_square_component
FROM observed o
CROSS JOIN totals t
ORDER BY o.region, o.product;

Which Pivot Technique to Ship

For a fixed key set that changes only with a release, hand-written CASE aggregation wins: it is plain SQL, the planner sees every predicate, and a reviewer can read the logic without running it. Reach for crosstab when PostgreSQL is guaranteed and the column list is static, because it removes the per-column boilerplate and returns a typed result in one call. The PIVOT operator in SQL Server, Oracle and BigQuery is the readable middle ground, but it requires pre-aggregation when the source has more than one row per cell. Dynamic SQL is the last resort and the only option when regions arrive as rows in a dictionary table.

TechniquePlan cacheableShape knownPortableCost of a column
CASE aggregationYesAt write timeEvery SQL engineOne CASE per column
crosstabYesAt write timePostgreSQL onlyOne AS type entry
PIVOT operatorYesAt write timeSQL Server, Oracle, BigQueryOne entry in VALUES
Dynamic SQLNoAt run timeAll, via dialect codeString building per key

Decision rule: if the column set changes without a deploy, use dynamic SQL; if it changes with a deploy, use CASE; if you are on PostgreSQL and the report is quarterly, use crosstab.

Edge Cases That Break Crosstabs

  • Duplicate cells. Pivoting a fact table that holds two rows for the same (year, month, region) makes SQL Server's PIVOT fail, because it cannot choose a value. Pre-aggregate with GROUP BY, or supply SUM in the VALUES list.
  • NULL versus zero. A quarter with no sales produces NULL, and NULL propagates through every downstream ratio. Wrap each branch in COALESCE(..., 0) before anyone divides by it.
  • Type narrowing. crosstab casts revenue to INT in the example, which truncates decimals and overflows past 2,147,483,647. Keep currency in numeric unless you are certain of the range.
  • Label collisions. Two keys that lowercase to the same output name — US and us — yield duplicate column labels, and the query fails at bind time rather than returning a confusing result.
  • Percentage columns. A percent-of-total column must be computed after the pivot with a window aggregate over the whole row, not inside each CASE, or the denominator will be the branch rather than the row.

Performance Comparison

MethodTime ComplexitySpaceDynamicDatabase
CASE WHENNoAll
crosstabNoPostgreSQL
Dynamic SQLYesAll
LATERAL JOINYesPostgreSQL

âš ī¸

Memory Warning: Pivoting large datasets can consume significant memory. Use work_mem setting and consider materializing intermediate results.

Choosing Columns That Survive New Data

Every conditional column is a promise that the key set will not change. When the key comes from a dictionary table, add a validation query to your release checks: compare the distinct keys against the columns your report expects and fail loudly when they diverge. A cheaper production guard is to compare SUM(revenue) with the sum of the generated columns on every run; a mismatch means an unpivoted key existed that day. Teams that ship weekly regional reports usually combine both: a static CASE for the known keys, an explicit Other column that collects anything unmatched, and an alert when Other grows past one percent of the total.

Common Mistakes

Pivoting a fact table that still has one row per event, producing duplicate cells or a planner error

Fix: Aggregate to exactly one row per pivot key and group key first, then pivot the aggregate

Hard-coding the region list and letting new regions fall out of every column

Fix: Emit a row total next to the branches, or add an Other column and alert when it is non-zero

Building the dynamic column list with plain string concatenation

Fix: Format labels with %I and values with %L so quotes and reserved words cannot corrupt the statement

Letting alphabetical ordering decide the column sequence

Fix: Sort the generated list by an integer ordinal held in the key dictionary

Key Takeaways

  • Pivoting changes the projection, not the access path, so cost is driven by source rows times branches emitted
  • Size the matrix before building it: keep unbounded keys long and pivot only after filtering and top-N
  • CASE is portable and cacheable, crosstab is PostgreSQL-only and static, PIVOT needs pre-aggregation, dynamic SQL is the only shape-from-data option
  • NULLs, duplicate cells and label collisions are the three failures that surface in production rather than in testing
  • Compute percent-of-total after the pivot with an empty window so the denominator is the row, not the branch
🔒

Premium Content

Dynamic PIVOT/UNPIVOT: Crosstab Reports, Matrix Queries

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