PIVOT, Crosstab & UNPIVOT in SQL
Rows↔columns without N queries
Conditional aggregation (FILTER/CASE) pivots portably everywhere. Vendor PIVOT/crosstab (TABLESAMPLE-free, MSSQL PIVOT, PG tablefunc crosstab) rotates compactly where supported. UNPIVOT melts wide columns to rows for normalization and charting. One grouped scan replaces N filtered queries in every spelling.
Portable pivot first
FILTER/CASE per column — everywhere, one scan.
Vendor rotate second
PIVOT/crosstab concise where installed — locked to engine.
UNPIVOT melts wide
Month columns → (month, value) rows for charts/normalization.
Label stably
Pivot columns are API — stable names/types for clients.
1SELECT COUNT(*) FILTER (WHERE department = 'Engineering') AS eng, COUNT(*) FILTER (WHERE department = 'Sales') AS sales FROM employees;
| eng | sales |
|---|---|
| 3 | 2 |
Two pivoted counts from one scan. Vendor PIVOT would rotate the same with less text but lock the query to one engine.
Eng vs Sales in one row
Single grouped scan.
1SELECT COUNT(*) FILTER (WHERE department = 'Engineering') AS eng, COUNT(*) FILTER (WHERE department = 'Sales') AS sales FROM employees;
| eng | sales |
|---|---|
| 3 | 2 |
Melt jan/feb columns
Wide → long for plotting.
1-- wide (jan, feb) → rows (month, amt) via UNPIVOT / UNION ALL
| month | amt |
|---|---|
| jan | 120 |
| feb | 135 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.