PIVOT & UNPIVOT Patterns
Reshape Data with PIVOT & UNPIVOT
PIVOT transforms rows into columns for matrix-style reporting. UNPIVOT does the reverse — turning columns back into rows for normalized analysis. Together, they are the most powerful data reshaping tools in SQL.
- Matrix Reporting — Convert time-series rows into quarterly/monthly columns
- Dynamic PIVOT — Generate columns from data values at query time
- UNPIVOT Patterns — Normalize wide tables back to row-level format
- Cross-Platform — Syntax for PostgreSQL, SQL Server, BigQuery, and MySQL
PIVOT turns "how did each department perform each quarter?" from a complex query into a clean, readable report.
What Is PIVOT?
PIVOT rotates a table by converting row values into column headers, aggregating the values at the intersection.
Mathematical Definition
Given a table with columns , PIVOT produces:
where each column contains:
"PIVOT is SQL's way of creating a cross-tabulation — the same operation as a spreadsheet pivot table." — Microsoft SQL Server Documentation
A pivot is a two-step reshape. Step one: the database groups rows by every column you did not name in the FOR clause. Step two: for each distinct value of the pivot column, it evaluates the aggregate and places the result in a dedicated output column. Rows that share a group key but differ only in the pivot column collapse into a single output row, which is why PIVOT always requires an aggregate — without one the engine has no rule for choosing among competing values.
PIVOT Transformation Visualized
Native PIVOT Syntax
SQL Server / PostgreSQL 14+
-- Native PIVOT syntax
SELECT *
FROM sales_data
PIVOT (
SUM(amount)
FOR product_category IN (
'Electronics' AS electronics,
'Clothing' AS clothing,
'Food' AS food,
'Books' AS books
)
) AS pivot_table;
BigQuery
-- BigQuery native PIVOT
SELECT *
FROM (
SELECT department, product_category, amount
FROM `project.dataset.sales`
)
PIVOT (
SUM(amount)
FOR product_category IN (
'Electronics' AS electronics,
'Clothing' AS clothing,
'Food' AS food
)
);
ℹ️
Key Insight: The PIVOT operator requires an aggregate function — you can't use PIVOT without aggregating. The aggregate (SUM, COUNT, AVG) determines what value appears at each intersection of row and column.
Where Native PIVOT Breaks
Native syntax looks clean until the data misbehaves. Four failure modes cover most production incidents:
- NULL pivot values never become a column. If the pivot column contains NULL, those rows vanish from the output because NULL cannot be used as a column header. Coalesce the pivot key to a label such as 'Unknown' before pivoting.
- Missing combinations return NULL, not zero. A department with no Electronics sales shows NULL in the electronics column, and charts render gaps unless you coalesce to 0.
- SQL Server rejects expressions in the FOR list. The values must be literals; subqueries and computed keys fail at parse time, so the column vocabulary is frozen when the query is written.
- Column order follows the IN list, not the data. Dynamic pivots that build the list from data must sort it explicitly, or report layouts shift whenever a new value appears.
Each of these pushes teams back to CASE-based aggregation, where every failure mode is visible in the query text during review.
Manual PIVOT with CASE
Cross-tabulation using conditional aggregation (works on all databases):
-- Quarterly revenue pivot using CASE
SELECT
department,
SUM(CASE WHEN EXTRACT(QUARTER FROM sale_date) = 1 THEN amount END) AS q1,
SUM(CASE WHEN EXTRACT(QUARTER FROM sale_date) = 2 THEN amount END) AS q2,
SUM(CASE WHEN EXTRACT(QUARTER FROM sale_date) = 3 THEN amount END) AS q3,
SUM(CASE WHEN EXTRACT(QUARTER FROM sale_date) = 4 THEN amount END) AS q4,
SUM(amount) AS total,
ROUND(
SUM(CASE WHEN EXTRACT(QUARTER FROM sale_date) = 1 THEN amount END) * 100.0 /
NULLIF(SUM(amount), 0), 1
) AS q1_pct
FROM sales
WHERE EXTRACT(YEAR FROM sale_date) = 2024
GROUP BY department
ORDER BY total DESC;
PIVOT Formula
For a PIVOT operation, each output cell is computed as:
Dynamic PIVOT with Unknown Columns
When column values are unknown at query time, build the PIVOT dynamically:
-- PostgreSQL: Dynamic pivot using string interpolation
DO $$
DECLARE
pivot_sql TEXT;
col_list TEXT;
BEGIN
-- Build column list dynamically from data
SELECT STRING_AGG(
DISTINCT '''' || product_category || ''' AS ' ||
REPLACE(product_category, ' ', '_'),
', '
)
INTO col_list
FROM sales_data;
-- Construct and execute pivot query
pivot_sql := format('
SELECT
department,
%s,
SUM(amount) AS total
FROM sales_data
GROUP BY department
ORDER BY total DESC
', col_list);
RAISE NOTICE '%', pivot_sql;
END $$;
⚠️
Performance Warning: Dynamic PIVOT requires dynamic SQL, which can't be prepared/cached. For large datasets, consider materializing the pivot columns first, or using a BI tool that handles pivoting at the presentation layer.
UNPIVOT Patterns
CROSS JOIN LATERAL (PostgreSQL, MySQL 8+)
-- Convert columns to rows (UNPIVOT)
SELECT
employee_id,
quarter,
amount
FROM quarterly_sales
CROSS JOIN LATERAL (
VALUES
('Q1', q1_amount),
('Q2', q2_amount),
('Q3', q3_amount),
('Q4', q4_amount)
) AS t(quarter, amount)
WHERE amount IS NOT NULL;
unnest with Arrays (PostgreSQL)
-- Using unnest for UNPIVOT
SELECT
employee_id,
quarter,
amount
FROM quarterly_sales
CROSS JOIN unnest(
ARRAY['Q1', 'Q2', 'Q3', 'Q4'],
ARRAY[q1_amount, q2_amount, q3_amount, q4_amount]
) AS t(quarter, amount);
UNION ALL (All Databases)
-- Universal UNPIVOT using UNION ALL
SELECT employee_id, 'Q1' AS quarter, q1_amount AS amount FROM quarterly_sales
UNION ALL
SELECT employee_id, 'Q2', q2_amount FROM quarterly_sales
UNION ALL
SELECT employee_id, 'Q3', q3_amount FROM quarterly_sales
UNION ALL
SELECT employee_id, 'Q4', q4_amount FROM quarterly_sales;
Choosing Among the Three Shapes
CROSS JOIN LATERAL over VALUES is the sweet spot on PostgreSQL and MySQL 8+: one source scan, one expansion step, and you can filter or rename pairs inline. unnest with parallel arrays is compact, but a length mismatch between the two arrays raises a runtime error rather than a compile-time failure, so keep both literals in the same place in the query. UNION ALL is the lowest-common-denominator fallback — fully portable and easy to review, but the planner executes one scan per branch, so unpivoting twelve monthly columns means twelve passes over the table. On very wide fact tables, materialize the narrow form during ETL instead of reshaping at query time.
Matrix-Style Reporting
Dashboards usually need one row per date with one column per platform. The CASE pivot over a pre-aggregated CTE is the reliable shape: aggregate grain first, pivot second, so the matrix never mixes levels of detail.
-- Daily active users pivot for dashboard reporting
WITH daily_stats AS (
SELECT
DATE(event_time) AS event_date,
platform,
COUNT(DISTINCT user_id) AS dau
FROM events
WHERE event_time >= CURRENT_DATE - INTERVAL '30' DAY
GROUP BY 1, 2
)
SELECT
event_date,
SUM(CASE WHEN platform = 'ios' THEN dau END) AS ios_dau,
SUM(CASE WHEN platform = 'android' THEN dau END) AS android_dau,
SUM(CASE WHEN platform = 'web' THEN dau END) AS web_dau,
SUM(dau) AS total_dau,
ROUND(SUM(CASE WHEN platform = 'ios' THEN dau END) * 100.0 / NULLIF(SUM(dau), 0), 1) AS ios_pct
FROM daily_stats
GROUP BY event_date
ORDER BY event_date;
Multi-Column PIVOT
Pivot multiple measures simultaneously using conditional aggregation:
-- Pivot multiple metrics in one query
SELECT
department,
SUM(CASE WHEN metric = 'avg_salary' THEN value END) AS avg_salary,
SUM(CASE WHEN metric = 'min_salary' THEN value END) AS min_salary,
SUM(CASE WHEN metric = 'max_salary' THEN value END) AS max_salary,
SUM(CASE WHEN metric = 'headcount' THEN value END) AS headcount,
SUM(CASE WHEN metric = 'new_hires' THEN value END) AS new_hires
FROM (
SELECT department, 'avg_salary' AS metric, AVG(salary) AS value FROM employees GROUP BY department
UNION ALL
SELECT department, 'min_salary', MIN(salary) FROM employees GROUP BY department
UNION ALL
SELECT department, 'max_salary', MAX(salary) FROM employees GROUP BY department
UNION ALL
SELECT department, 'headcount', COUNT(*)::NUMERIC FROM employees GROUP BY department
UNION ALL
SELECT department, 'new_hires', COUNT(*)::NUMERIC FROM employees
WHERE hire_date >= CURRENT_DATE - INTERVAL '90' DAY GROUP BY department
) sub
GROUP BY department;
PIVOT with Percentage Calculation
-- Pivot with row-wise percentage
WITH pivoted AS (
SELECT
department,
SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) AS active,
SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) AS inactive,
SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending,
COUNT(*) AS total
FROM employees
GROUP BY department
)
SELECT
department,
active, inactive, pending, total,
ROUND(active * 100.0 / NULLIF(total, 0), 1) AS active_pct,
ROUND(inactive * 100.0 / NULLIF(total, 0), 1) AS inactive_pct,
ROUND(pending * 100.0 / NULLIF(total, 0), 1) AS pending_pct
FROM pivoted
ORDER BY total DESC;
Performance Comparison
PIVOT Method Performance
| Method | Database Support | Readability | Flexibility | Performance |
|---|---|---|---|---|
| Native PIVOT | SQL Server, PG 14+ | High | Low (fixed columns) | Fast |
| CASE-based | All databases | Medium | High | Fast |
| Dynamic SQL | All databases | Low | Very High | Moderate |
| Crosstab (PG) | PostgreSQL | Medium | Medium | Fast |
For most use cases, CASE-based pivoting offers the best balance of portability, readability, and performance.
PIVOT Across Engines
| Engine | Native syntax | Dynamic pivot technique | Quirk to remember |
|---|---|---|---|
| SQL Server | PIVOT / UNPIVOT operator | Dynamic SQL with sp_executesql | FOR list must be literals |
| PostgreSQL 14+ | PIVOT / UNPIVOT operator | DO block + EXECUTE, or crosstab() | crosstab needs tablefunc extension |
| BigQuery | PIVOT after a subquery | Scripting with EXECUTE IMMEDIATE | Pivot keys must be quoted strings |
| MySQL 8.x | None | Prepared statements with CONCAT | Default to CASE aggregation |
| Snowflake | PIVOT / UNPIVOT operator | Client-side query builder | PIVOT consumes a subquery only |
Portability rule: if the warehouse might change in the next two years, write the CASE form. Native PIVOT saves typing on the engine you run today, and the rewrite cost lands on whoever inherits the report pack later. For one-off analyst work on a pinned engine, native syntax is fine.
Quiz: Test Your Knowledge
Follow-Up Questions
- How would you pivot data when the number of columns is unknown at query time?
- What's the performance impact of using CASE-based pivoting vs native PIVOT?
- How do you handle NULL values in UNPIVOT operations?
- Explain how to pivot multiple measures without using UNION ALL.
- What's the best approach for pivoting data in a columnar database like BigQuery?
- How would you create a running total within each pivoted column?
Common Pitfalls
Common Mistakes
Calling PIVOT without an aggregate function and expecting the engine to pick a value
Fix: Always wrap the value column in SUM, COUNT, AVG or another aggregate — the intersection can hold many rows
Assuming a pivoted cell with no source rows will read 0
Fix: Missing combinations come back as NULL; wrap the pivot in an outer SELECT with COALESCE(..., 0) when charts must show zeros
Letting NULL pivot keys silently drop rows
Fix: Coalesce the pivot column to a literal label such as 'Unknown' before the PIVOT or CASE expression
Pivoting at query time on a twelve-column monthly fact table
Fix: Persist the narrow (long) form in ETL and pivot only the two or three columns the dashboard renders
Key Takeaways
- PIVOT requires aggregation — always use SUM, COUNT, or another aggregate function
- CASE-based pivoting is the most portable and readable approach across all databases
- Dynamic PIVOT needs dynamic SQL — consider materializing columns or using BI tools
- UNION ALL is the universal UNPIVOT method — works everywhere
- NULL handling — use NULLIF(divisor, 0) to prevent division by zero in percentage calculations
- Native PIVOT (SQL Server, PG 14+) is faster but less flexible than CASE-based approaches