Skip to content
Gold 6 min read · Reshaping 3 practice problems ↓

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

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

cityquarterrevenue
DelhiQ1380
DelhiQ2450
DelhiQ4690

Wide: one column per quarter

cityQ1Q2Q3Q4
Delhi380450NULLNULL: 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

Easy to filter, group, join and append to. This is how data should be stored, and what tools like Spark and dbt prefer.

Wide tables

Easy for people to read and compare across. This is how reports, spreadsheets and some ML features want it.

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

See all 4 problems →

Keep going

Up next · new module: How a query runs · 8 min read
Reading EXPLAIN
Read a query plan from the bottom up: scans and pushed filters, shuffles, join strategies, and why a query is slow.

Related lessons

Previous: Sessionization

Primary sources: PIVOT clause · UNPIVOT clause · stack