Skip to content
Silver 5 min read · Reshaping 3 practice problems ↓

pivot

Reports are often wide: one row per region, one column per quarter. Data is usually stored long: one row per region and quarter. pivot turns the long shape into the wide one. This lesson shows how, why listing the column values makes it faster, and how to do it in SQL.

Step 1 · PySpark functions · Silver · Reshape and refine, lesson 4 of 7

Read first: groupBy + agg · when / otherwise (skip if you know them)

In plain words first

Picture a list of sales: "North, Q1, 100", "North, Q2, 120", "South, Q1, 90". To make a report, you draw a grid: regions down the side, quarters across the top, and write each number in its cell.

That grid is a pivot: values from one column (quarter) become column headings, and an aggregateaggregate: A function that turns many rows into one value per group: count, sum, avg, min, max. Learn more → fills each cell.

What it does

Long data has one row per (region, quarter). A pivot makes it wide: one row per region, one column per quarter, each cell an aggregate.

Step by step

sales (long)

regionqtramount
NorthQ1100
NorthQ2150
NorthQ150
SouthQ180
SouthQ3120

pivoted (wide)

regionQ1Q2Q3
North150150nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →
South80null120

North's two Q1 rows are summed. Combinations with no rows become null, not 0.

Run the example

PySparkSpark SQL

Input: sales

regionqtramount
NorthQ1100
NorthQ2150
NorthQ150
SouthQ180
SouthQ3120
from pyspark.sql import functions as F
result = (sales
    .groupBy("region")
    .pivot("qtr", ["Q1", "Q2", "Q3", "Q4"])
    .agg(F.sum("amount"))
    .orderBy("region"))
SELECT * FROM sales
PIVOT (
  SUM(amount) FOR qtr IN ('Q1', 'Q2', 'Q3', 'Q4')
)
ORDER BY region

Q4 has no data and still appears, full of nulls, because we listed it. Listing values gives you a fixed, predictable schemaschema: The list of a DataFrame's columns and their types, such as order_id: long and city: string. Learn more →.

Always pass the values

pivot("qtr")

Spark runs an extra job to collect the distinct quarters, then pivots. The output columns change if the data changes. Limited to 10,000 distinct values by default (spark.sql.pivotMaxValues).

pivot("qtr", ["Q1", ...])

No extra job, a stable schema, and values you did not list are ignored.

Several aggregates

With more than one aggregate, each output column is named value_alias: .agg(F.sum("amount").alias("revenue"), F.count("*").alias("n")) gives Q1_revenue, Q1_n, and so on.

Rename the pivoted columns

The new columns are named after the pivot values (Q1, Q2). In Spark SQL, give a value an alias inside the IN list and that alias becomes the column name. In PySpark, rename the columns after the pivot:

PySparkSpark SQL

Input: sales

regionqtramount
NorthQ1100
NorthQ2150
NorthQ150
SouthQ180
SouthQ3120
from pyspark.sql import functions as F
result = (sales
    .groupBy("region")
    .pivot("qtr", ["Q1", "Q2"])
    .agg(F.sum("amount"))
    .withColumnRenamed("Q1", "q1_sales")
    .withColumnRenamed("Q2", "q2_sales"))
SELECT * FROM sales
PIVOT (
  SUM(amount) FOR qtr IN ('Q1' AS q1_sales, 'Q2' AS q2_sales)
)

One aggregate

The column takes the value's alias. An alias on the aggregate is ignored: SUM(amount) AS total FOR qtr IN ('Q1', 'Q2') still gives Q1, Q2.

Several aggregates

Each column is valueAlias_aggAlias: SUM(amount) AS total, COUNT(*) AS n FOR qtr IN ('Q1' AS q1, 'Q2' AS q2) gives q1_total, q1_n, q2_total, q2_n.

Rename in the SELECT

The select list runs after the pivot, so you can also rename there, and fix nulls at the same time: SELECT region, COALESCE(Q1, 0) AS q1_sales FROM sales PIVOT (...).

Pivot by hand

A pivot is a set of conditional aggregates, one per value. Writing it out is sometimes clearer, and lets each column use a different rule:

PySparkSpark SQL

Input: sales

regionqtramount
NorthQ1100
NorthQ2150
NorthQ150
SouthQ180
SouthQ3120
from pyspark.sql import functions as F
result = sales.groupBy("region").agg(
    F.sum(F.when(F.col("qtr") == "Q1", F.col("amount"))).alias("Q1"),
    F.sum(F.when(F.col("qtr") == "Q2", F.col("amount"))).alias("Q2"),
)
SELECT region,
       SUM(CASE WHEN qtr = 'Q1' THEN amount END) AS Q1,
       SUM(CASE WHEN qtr = 'Q2' THEN amount END) AS Q2
FROM sales
GROUP BY region

Under the hood Optional deep dive

Spark rewrites a pivot into an aggregation, so it costs one shuffleshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more → like any groupBy. The SQL PIVOT clause groups implicitly by every column not mentioned in the PIVOT, so select only the columns you want before pivoting, or extra columns silently become grouping keys.

Common mistakes

  • Not passing the values list — An extra job, and a schema that changes when new values appear.
  • Expecting zeros — Missing combinations are null. Wrap with coalesce or fillna if 0 is correct.
  • Extra columns in a SQL PIVOT — Every column not used in the pivot becomes a grouping key, multiplying rows.

Key takeaways

  • pivot makes one column per value of the pivot column.
  • Pass the values list: faster and a stable schema.
  • Empty cells are null.
  • A pivot is just conditional aggregates; you can write them by hand.

Interview prep

THE QUESTION

"Show monthly revenue per product as columns Jan to Dec."

groupBy product, pivot month with the 12 values listed explicitly, agg sum. Mention why the explicit list matters (no extra job, stable schema) and that empty months are null, so coalesce to 0 if the report needs it.

Avoid: pivoting without listing the values. Spark then runs an extra job to find distinct values, and the schema depends on the data.

Follow-ups · answer out loud, then open

Follow-up"How many distinct values can you pivot on?"
Up to spark.sql.pivotMaxValues (10,000) when Spark discovers them. In practice, a pivot with thousands of columns is a design smell: keep the data long and pivot only for presentation.
Scenario"Pivot two aggregates, sum of amount and count of orders, per month."
df.groupBy("product").pivot("month", months).agg(F.sum("amount").alias("amt"), F.count("*").alias("n")). Spark names columns like Jan_amt and Jan_n.
Trap"pivot fills missing combinations with 0."
It gives null for combinations with no rows. Use fillna(0) on the pivoted columns if a zero is correct.

Check yourself

3 questions

What does pivot without a values list cost extra?

Show the answer

A job to find the distinct values. Spark must know the output columns, so it first computes the distinct values of the pivot column.

A region has no Q3 sales. What is its Q3 cell after sum-pivoting?

Show the answer

null. There are no rows to sum, so the aggregate is null.

Which is equivalent to pivoting quarter with sum(amount)?

Show the answer

sum(when(quarter = value, amount)) for each value, grouped by the row key. Each pivot column is a conditional aggregate over the group.

Practise this

Problems that use pivot, graded on hidden tests

Keep going

Up next · Reshape and refine · lesson 5 of 7 · 4 min read
trunc / add_months
Truncate dates to the month or year and shift them by whole months, including month-end rules.

Related lessons

Previous: eqNullSafe (<=>)

Primary sources: GroupedData.pivot · PIVOT clause