Learn SQL
-- aggregations.pivot_crosstab_unpivot

PIVOT, Crosstab & UNPIVOT in SQL

Rows↔columns without N queries

--concept

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.

--how it works
1

Portable pivot first

FILTER/CASE per column — everywhere, one scan.

2

Vendor rotate second

PIVOT/crosstab concise where installed — locked to engine.

3

UNPIVOT melts wide

Month columns → (month, value) rows for charts/normalization.

4

Label stably

Pivot columns are API — stable names/types for clients.

--visualization
FILTER pivots portably — one scan, vendor PIVOT locks engines
engsales
32
Stage 1 / 1
UNPIVOT melts wide month columns to (month,value) rows for charts.
--example
query.sql
1SELECT COUNT(*) FILTER (WHERE department = 'Engineering') AS eng, COUNT(*) FILTER (WHERE department = 'Sales') AS sales FROM employees;
Result
engsales
32

Two pivoted counts from one scan. Vendor PIVOT would rotate the same with less text but lock the query to one engine.

--variants

Eng vs Sales in one row

Single grouped scan.

query.sql
1SELECT COUNT(*) FILTER (WHERE department = 'Engineering') AS eng, COUNT(*) FILTER (WHERE department = 'Sales') AS sales FROM employees;
Result
engsales
32
1Full table once.
2Each FILTER tallies its slice.
3CASE twin identical where FILTER absent.

Melt jan/feb columns

Wide → long for plotting.

query.sql
1-- wide (jan, feb) → rows (month, amt) via UNPIVOT / UNION ALL
Result
monthamt
jan120
feb135
1Each month column becomes rows.
2Charts want long shape.
3UNPIVOT syntax varies — UNION ALL portable.
--key facts
PortableFILTER/CASE everywhere
VendorPIVOT/crosstab concise, locked
UNPIVOTwide → long for charts
--use cases
Funnel pivots + monthly crosstabs
Chart-ready long tables from wide exports
--under the hood
Pivots aggregate in one grouped pass — N filtered queries rescan N times.
crosstab needs tablefunc + type setup — worth it for repeated matrix reports.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.