โคด๏ธ PIVOT & UNPIVOT
Reports often need data turned sideways: one row per region with a column for each quarter, instead of one row per region and quarter. PIVOT turns rows into columns, and UNPIVOT turns columns back into rows. This tutorial covers both, plus the older tricks you will still see in existing code.
Every query below runs on Spark 3.5 and shows its exact result.
1. Sample Data
sales holds revenue in long format, with one row per region, quarter and product. quarterly_wide holds the same kind of numbers in wide format, with one column per quarter:
CREATE OR REPLACE TEMP VIEW sales AS
SELECT * FROM VALUES
('North', 'Q1', 'Laptop', 100),
('North', 'Q1', 'Phone', 80),
('North', 'Q2', 'Laptop', 150),
('North', 'Q3', 'Phone', 90),
('South', 'Q1', 'Laptop', 120),
('South', 'Q2', 'Laptop', 60),
('South', 'Q2', 'Phone', 70),
('South', 'Q4', 'Laptop', 200)
AS sales(region, quarter, product, revenue)
CREATE OR REPLACE TEMP VIEW quarterly_wide AS
SELECT * FROM VALUES
('North', 180, 150, 90, NULL),
('South', 120, 130, NULL, 200)
AS quarterly_wide(region, q1, q2, q3, q4)
2. Long vs Wide Data
| Format | Shape | Good for |
|---|---|---|
| Long | Few columns, many rows: region, quarter, revenue | Storing data, filtering, grouping, joining |
| Wide | Many columns, few rows: region, Q1, Q2, Q3, Q4 | Reports, spreadsheets, charts |
Data is usually stored long, because adding a new quarter only adds rows. People usually read it wide. PIVOT goes from long to wide; UNPIVOT goes from wide to long.
3. Your First PIVOT
The basic shape is:
-- Syntax
SELECT *
FROM (SELECT row_columns, pivot_column, value_column FROM table)
PIVOT (
aggregate(value_column)
FOR pivot_column IN (value1, value2, ...)
)
To get one row per region and one column per quarter:
SELECT *
FROM (SELECT region, quarter, revenue FROM sales)
PIVOT (
SUM(revenue)
FOR quarter IN ('Q1', 'Q2', 'Q3', 'Q4')
)
ORDER BY region
+------+---+---+----+----+
|region|Q1 |Q2 |Q3 |Q4 |
+------+---+---+----+----+
|North |180|150|90 |NULL|
|South |120|130|NULL|200 |
+------+---+---+----+----+
Here is what happened:
- Each value in the
INlist became a column:Q1,Q2,Q3,Q4. - Rows were grouped by every other column in the input, which here is only
region. SUM(revenue)filled each cell. North'sQ1is 180 because North had two Q1 rows (100 + 80).- Cells with no rows are
NULL, such as North in Q4.
The IN list is required in Spark SQL. Spark does not look at the data to discover the values, so a quarter you leave out of the list is simply not shown.
4. The Most Common PIVOT Mistake
PIVOT groups by every column you did not mention in the aggregate or the FOR clause. If you pivot the whole table, product becomes a grouping column too:
SELECT *
FROM sales
PIVOT (
SUM(revenue)
FOR quarter IN ('Q1', 'Q2', 'Q3', 'Q4')
)
ORDER BY region, product
+------+-------+----+----+----+----+
|region|product|Q1 |Q2 |Q3 |Q4 |
+------+-------+----+----+----+----+
|North |Laptop |100 |150 |NULL|NULL|
|North |Phone |80 |NULL|90 |NULL|
|South |Laptop |120 |60 |NULL|200 |
|South |Phone |NULL|70 |NULL|NULL|
+------+-------+----+----+----+----+
Now you get one row per region and product, which is not what we wanted. This is why the first example selects only the needed columns in a subquery first.
Common mistake: Pivoting a table that has an ID or timestamp column. Every row has a different ID, so nothing gets grouped and the result is full of
NULLs. Always select just the row label, the pivot column and the value column before pivoting.
5. Naming the Pivoted Columns
Column names like Q1 are fine, but values such as 'North America' would make awkward column names. Add an alias to each value in the IN list:
SELECT region,
coalesce(q1, 0) AS q1,
coalesce(q2, 0) AS q2,
coalesce(q3, 0) AS q3,
coalesce(q4, 0) AS q4
FROM (SELECT region, quarter, revenue FROM sales)
PIVOT (
SUM(revenue)
FOR quarter IN ('Q1' AS q1, 'Q2' AS q2, 'Q3' AS q3, 'Q4' AS q4)
)
ORDER BY region
+------+---+---+---+---+
|region|q1 |q2 |q3 |q4 |
+------+---+---+---+---+
|North |180|150|90 |0 |
|South |120|130|0 |200|
+------+---+---+---+---+
The outer SELECT uses coalesce to show 0 instead of NULL for quarters with no sales. Reports often want this, but keep the NULL if you need to tell "no data" apart from "zero revenue".
6. More Than One Aggregate
You can compute several aggregates at once. Give each one an alias, and Spark names the columns <value alias>_<aggregate alias>:
SELECT *
FROM (SELECT region, quarter, revenue FROM sales)
PIVOT (
SUM(revenue) AS total,
COUNT(*) AS orders
FOR quarter IN ('Q1' AS q1, 'Q2' AS q2)
)
ORDER BY region
+------+--------+---------+--------+---------+
|region|q1_total|q1_orders|q2_total|q2_orders|
+------+--------+---------+--------+---------+
|North |180 |2 |150 |1 |
|South |120 |1 |130 |2 |
+------+--------+---------+--------+---------+
Two quarters times two aggregates gives four new columns. Each extra aggregate multiplies the column count, so keep the IN list short.
You can also pivot on two columns at once by listing value pairs:
SELECT *
FROM (SELECT region, quarter, product, revenue FROM sales)
PIVOT (
SUM(revenue)
FOR (quarter, product) IN (('Q1', 'Laptop') AS q1_laptop,
('Q1', 'Phone') AS q1_phone)
)
ORDER BY region
+------+---------+--------+
|region|q1_laptop|q1_phone|
+------+---------+--------+
|North |100 |80 |
|South |120 |NULL |
+------+---------+--------+
7. PIVOT Is Just Conditional Aggregation
Under the hood, a pivot is a GROUP BY with one conditional aggregate per column. This query gives the same result as section 5, without the coalesce:
SELECT region,
SUM(CASE WHEN quarter = 'Q1' THEN revenue END) AS q1,
SUM(CASE WHEN quarter = 'Q2' THEN revenue END) AS q2,
SUM(CASE WHEN quarter = 'Q3' THEN revenue END) AS q3,
SUM(CASE WHEN quarter = 'Q4' THEN revenue END) AS q4
FROM sales
GROUP BY region
ORDER BY region
+------+---+---+----+----+
|region|q1 |q2 |q3 |q4 |
+------+---+---+----+----+
|North |180|150|90 |NULL|
|South |120|130|NULL|200 |
+------+---+---+----+----+
Each CASE returns the revenue only for its quarter and NULL otherwise, and SUM ignores NULLs. A quarter with no rows sums nothing and gives NULL, exactly like PIVOT.
Why learn both?
CASE WHENworks in every SQL database, so it is the safe answer in interviews.- It lets each column have its own rule, for example
SUM(CASE WHEN quarter IN ('Q1', 'Q2') THEN revenue END) AS first_half. PIVOTis shorter when every column follows the same pattern.
Interview tip: "Convert rows to columns" questions can always be solved with
GROUP BYplusSUM(CASE WHEN ...). MentionPIVOTas the shorter Spark SQL alternative.
8. UNPIVOT: Columns Back into Rows
UNPIVOT (available since Spark 3.4) takes several columns and stacks them into two columns: one for the old column name and one for its value.
SELECT *
FROM quarterly_wide
UNPIVOT (
revenue FOR quarter IN (q1, q2, q3, q4)
)
ORDER BY region, quarter
+------+-------+-------+
|region|quarter|revenue|
+------+-------+-------+
|North |q1 |180 |
|North |q2 |150 |
|North |q3 |90 |
|South |q1 |120 |
|South |q2 |130 |
|South |q4 |200 |
+------+-------+-------+
Read revenue FOR quarter IN (q1, q2, q3, q4) as: "put the values in a column called revenue, and the name of the column they came from in a column called quarter".
Each region had four quarter columns, so you might expect 8 rows, but there are only 6. UNPIVOT drops rows whose value is NULL by default. North's q4 and South's q3 were NULL, so they are gone.
9. Keeping NULLs and Renaming Values
Add INCLUDE NULLS to keep those rows, and alias each column to control the text in the name column:
SELECT *
FROM quarterly_wide
UNPIVOT INCLUDE NULLS (
revenue FOR quarter IN (q1 AS Q1, q2 AS Q2, q3 AS Q3, q4 AS Q4)
)
ORDER BY region, quarter
+------+-------+-------+
|region|quarter|revenue|
+------+-------+-------+
|North |Q1 |180 |
|North |Q2 |150 |
|North |Q3 |90 |
|North |Q4 |NULL |
|South |Q1 |120 |
|South |Q2 |130 |
|South |Q3 |NULL |
|South |Q4 |200 |
+------+-------+-------+
Now all 8 rows are there, and the quarter labels are Q1 to Q4 instead of the lowercase column names.
Common mistake: Counting rows after an UNPIVOT and getting fewer than expected. If a missing value should count as "zero" or "not reported", use
INCLUDE NULLS.
10. The Older Way: stack()
Before Spark 3.4, the usual way to unpivot was the stack function. You will see it in a lot of existing code:
SELECT region,
stack(4, 'Q1', q1, 'Q2', q2, 'Q3', q3, 'Q4', q4) AS (quarter, revenue)
FROM quarterly_wide
ORDER BY region, quarter
+------+-------+-------+
|region|quarter|revenue|
+------+-------+-------+
|North |Q1 |180 |
|North |Q2 |150 |
|North |Q3 |90 |
|North |Q4 |NULL |
|South |Q1 |120 |
|South |Q2 |130 |
|South |Q3 |NULL |
|South |Q4 |200 |
+------+-------+-------+
stack(n, ...) splits the remaining arguments into n rows. Here it takes pairs: 'Q1', q1 becomes the first row, 'Q2', q2 the second, and so on. AS (quarter, revenue) names the two output columns.
Unlike UNPIVOT, stack keeps NULL values. Add WHERE revenue IS NOT NULL in an outer query if you want them dropped. All value columns in one stack call must have compatible types.
11. Putting It Together: A Quarterly Report
A typical report pivots the long data and adds a total per row. Here we start from sales, pivot to wide, and add a yearly total:
SELECT region,
coalesce(q1, 0) AS q1,
coalesce(q2, 0) AS q2,
coalesce(q3, 0) AS q3,
coalesce(q4, 0) AS q4,
coalesce(q1, 0) + coalesce(q2, 0) + coalesce(q3, 0) + coalesce(q4, 0) AS year_total
FROM (SELECT region, quarter, revenue FROM sales)
PIVOT (
SUM(revenue)
FOR quarter IN ('Q1' AS q1, 'Q2' AS q2, 'Q3' AS q3, 'Q4' AS q4)
)
ORDER BY year_total DESC
+------+---+---+---+---+----------+
|region|q1 |q2 |q3 |q4 |year_total|
+------+---+---+---+---+----------+
|South |120|130|0 |200|450 |
|North |180|150|90 |0 |420 |
+------+---+---+---+---+----------+
Without the coalesce calls, any NULL quarter would make the whole year_total NULL, because adding NULL to a number gives NULL.
12. Try It in the Online Compiler
Copy this into the PySpark Online Compiler:
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Spark SQL Pivot").getOrCreate()
spark.sql("""
CREATE OR REPLACE TEMP VIEW sales AS
SELECT * FROM VALUES
('North', 'Q1', 'Laptop', 100),
('North', 'Q1', 'Phone', 80),
('North', 'Q2', 'Laptop', 150),
('North', 'Q3', 'Phone', 90),
('South', 'Q1', 'Laptop', 120),
('South', 'Q2', 'Laptop', 60),
('South', 'Q2', 'Phone', 70),
('South', 'Q4', 'Laptop', 200)
AS sales(region, quarter, product, revenue)
""")
wide = spark.sql("""
SELECT *
FROM (SELECT region, quarter, revenue FROM sales)
PIVOT (SUM(revenue) FOR quarter IN ('Q1' AS q1, 'Q2' AS q2, 'Q3' AS q3, 'Q4' AS q4))
""")
wide.orderBy("region").show(truncate=False)
# Turn the pivoted result back into long format
wide.createOrReplaceTempView("wide")
spark.sql("""
SELECT *
FROM wide
UNPIVOT (revenue FOR quarter IN (q1, q2, q3, q4))
ORDER BY region, quarter
""").show(truncate=False)
Summary
- PIVOT turns row values into columns:
PIVOT (agg(value) FOR col IN (v1, v2, ...)). TheINlist is required. - PIVOT groups by every column not used in the aggregate or
FOR, so select only the columns you need in a subquery first. - Alias the
INvalues for clean column names, and usecoalesceif empty cells should show 0. GROUP BYwithSUM(CASE WHEN ...)does the same job and works in any SQL database.- UNPIVOT (Spark 3.4+) turns columns into rows and drops
NULLvalues unless you addINCLUDE NULLS. stack()is the older way to unpivot and keepsNULLvalues.
Next, you will learn how to work with arrays, maps and structs, the nested data types you meet in JSON and event data.