Pivot and unpivot
Turn rows into columns for reports and columns back into rows, with PIVOT, CASE WHEN, UNPIVOT and stack.
Foundations · SQL for data engineers · Gold · Interview patterns, lesson 3 of 3
On this page
Read first: Conditional aggregates and COUNT DISTINCT · GROUP BY and HAVING (skip if you know them)
In plain words first
The same numbers can be laid out two ways:
Long: one row per value
| city | quarter | revenue |
|---|---|---|
| Delhi | Q1 | 380 |
| Delhi | Q2 | 450 |
| Delhi | Q4 | 690 |
Wide: one column per quarter
| city | Q1 | Q2 | Q3 | Q4 |
|---|---|---|---|---|
| Delhi | 380 | 450 | NULLNULL: A missing or unknown value. It is not 0 or an empty string, and any comparison with it is unknown instead of true or false. Learn more → | 690 |
Pivot goes left to right; unpivot goes right to left.
Long tables
Wide tables
So a pipeline usually keeps data long and pivots only at the very end, for the report. Spreadsheets that arrive wide get unpivoted on the way in.
Unlock the full lesson
You have read the free part. The rest of this advanced lesson:
- PIVOT: rows into columns
- The same pivot with CASE WHEN
- Several aggregates at once
- UNPIVOT: columns into rows
- Common mistakes
- Key takeaways
- Interview prep with 3 follow-up questions
- Check yourself: 4 questions
Unlock it with the Complete pass (every advanced problem and lesson) or on its own.
Practise this
Problems that use this, graded on hidden tests
- Pivot Quarterly RevenuePivot, Unpivot & Rollup Medium
- Unpivot Wide Columns to RowsPivot, Unpivot & Rollup Medium
- Pivot with Several AggregationsPivot, Unpivot & Rollup AdvancedHard
Keep going
Up next · new module: How a query runs · 8 min readReading EXPLAIN
Read a query plan from the bottom up: scans and pushed filters, shuffles, join strategies, and why a query is slow.
Related lessons
Conditional aggregates and COUNT DISTINCTSQL for data engineers · 6 min read
GROUP BY and HAVINGSQL for data engineers · 8 min read
Gaps and islands
Previous: Sessionization
Primary sources: PIVOT clause · UNPIVOT clause · stack