Module 04 · Lesson 12 of 16Detailed study · about 18 min

PIVOT and UNPIVOT: reshape reports

PIVOT turns category values into columns using an aggregate. UNPIVOT turns selected columns into rows; it cannot recover detail lost during aggregation.

Understand the idea

A long sales table has one row per region and month. A report may want JAN and FEB next to each other. PIVOT performs that reshape, but it also aggregates if several source rows share a region/month.

Key ideas in simple English
ConceptWhat it means
PIVOTCreate category columns from input rows and aggregate their values.
UNPIVOTCreate a name/value row from each selected input column.
NULL handlingUNPIVOT excludes NULL values unless INCLUDE NULLS is requested.

A concrete example

East January is 40 + 10 = 50. Missing West February remains NULL.

Remember: UNPIVOT reshapes the totals it receives. It cannot reconstruct source records that were combined by SUM.

Explain it step by step · full theory

Let us understand the idea

A long sales table has one row per region and month. A report may want JAN and FEB next to each other. PIVOT performs that reshape, but it also aggregates if several source rows share a region/month.

Only project the intended grouping columns, category and measure into PIVOT. Extra input columns can become grouping keys and split your output unexpectedly. This example uses a fixed month list so the output schema is predictable.

Reason through the SQL

UNPIVOT works in the other direction: JAN and FEB become MONTH_NAME and SALES. Its column list must have compatible types. INCLUDE NULLS keeps an explicit row for a missing month value.

If two January orders were summed into one January total, unpivoting the total does not recreate the two original orders. Reshaping a report is different from reversing an aggregation.

Words used in this lesson
PIVOT
Create category columns from input rows and aggregate their values.
UNPIVOT
Create a name/value row from each selected input column.
NULL handling
UNPIVOT excludes NULL values unless INCLUDE NULLS is requested.

See how it works

Choose a step to explore the idea at your own pace.

Open the interactive explanation
Interactive explainer1 / 3

PIVOT and UNPIVOT: reshape reports

Input rows
Business question

Begin with the question

PIVOT turns category values into columns using an aggregate. UNPIVOT turns selected columns into rows; it cannot recover detail lost during aggregation.

Automatic playback is off for reduced motion. Select any step or use Previous and Next. Illustrations explain behavior; they are not live measurements.

Read the complete diagram explanation
  1. Begin with the question

    PIVOT turns category values into columns using an aggregate. UNPIVOT turns selected columns into rows; it cannot recover detail lost during aggregation.

  2. Choose the operation

    A long sales table has one row per region and month. A report may want JAN and FEB next to each other. PIVOT performs that reshape, but it also aggregates if several source rows share a region/month.

  3. Check the meaning

    UNPIVOT reshapes the totals it receives. It cannot reconstruct source records that were combined by SUM.

Try the SQL or command

Read → predict → run in your learning environment → compare. You can also learn by reading without an account.

New to SQL? Where to run it and how to read it

A query is a question written in SQL. Snowflake runs it and returns a result table. This website shows examples; it does not connect to your account.

  1. No account yet? Read and predict the output first. Follow the account and Snowsight lesson when you are ready.
  2. For SQL practice, use a learning account in Snowsight and select an authorized role and warehouse. A role determines permissions; a warehouse supplies processing power. Follow the example’s database/schema setup when it refers to stored objects.
  3. Read the entire example, including comments beginning with --. Run the selected statement or labeled block in the stated order. Examples labeled Python, shell or HTTP belong in that client, not in a SQL editor.
  4. Compare values and row counts with the explained result. If an example deliberately causes an error, follow its rollback and cleanup steps before continuing.
SELECT / FROM
Choose the values to return / identify their input.
VALUES / COLUMN1
VALUES supplies tiny example rows. COLUMN1 means their first column, COLUMN2 their second.
AS / WITH
AS gives a result a readable name. WITH names a temporary query step within one statement.
NULL / ::
NULL means missing or unknown. The :: notation converts a value to a named data type.
Session
One connection and its settings. Keep related transaction steps in the same session.
Database.schema.table
A full address for stored data. It is separate from the warehouse that processes queries.

Need the L2_OBJECTS_LAB setup? Open the first database-object lesson →

Help with common practice errors
  • No active warehouse: select a warehouse your role can use. Do not assume you need to create a new one.
  • Object missing or not authorized: check the full name, required setup and active role. Ask the account owner for access if needed.
  • Object already exists: setup may already have run. Read the current state or choose a fresh lab name consistently; do not add OR REPLACE blindly.
  • Different result: check whether an earlier INSERT or UPDATE changed the data. VALUES examples provide their own fresh input for each statement.

Before running this lesson

Read first, then run manually in an authorized Snowflake learning session with a warehouse. Each WITH/VALUES example includes its own inputs and creates no stored tables. Expected results are illustrative, not live execution.

Turn months into report columns

SQL · example
WITH sales AS (SELECT COLUMN1 AS REGION, COLUMN2 AS MONTH_NAME, COLUMN3 AS AMOUNT
FROM VALUES ('East','Jan',40),('East','Jan',10),('East','Feb',60),('West','Jan',25))
SELECT REGION, JAN, FEB FROM sales
PIVOT(SUM(AMOUNT) FOR MONTH_NAME IN ('Jan' AS JAN,'Feb' AS FEB))
ORDER BY REGION;

What to expect and why

East January is 40 + 10 = 50. Missing West February remains NULL.

Expected result for the supplied input (not live output)
REGIONJANFEB
East5060
West25NULL

Turn report columns back into rows

SQL · example
WITH report AS (SELECT COLUMN1 AS REGION, COLUMN2::NUMBER AS JAN, COLUMN3::NUMBER AS FEB
FROM VALUES ('East',50,60),('West',25,NULL))
SELECT REGION, MONTH_NAME, SALES FROM report
UNPIVOT INCLUDE NULLS (SALES FOR MONTH_NAME IN (JAN,FEB))
ORDER BY REGION, MONTH_NAME;

What to expect and why

Returns four rows, including West/FEB/NULL. Without INCLUDE NULLS that row is omitted, leaving three rows.

Check your understanding

Choose an answer, then check your reasoning. This is practice, not a scored test.

Can UNPIVOT recover individual orders after PIVOT summed them?

Try it yourself

Remove INCLUDE NULLS and predict the row count.

Compare your reasoning

UNPIVOT defaults to excluding NULL values. West/FEB disappears, leaving three rows.

Official sources and curriculum

Module 04 · See module scope