Bird
Raised Fist0
SQLquery~10 mins

Pivot and unpivot concepts in SQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Pivot and unpivot concepts
Start with raw table
↓
Choose columns to transform
↓
Pivot: Rows to Columns
↓
Aggregated summary
↓
Unpivot: Columns to Rows
↓
Normalized detailed table
Pivot turns row values into columns to summarize data. Unpivot reverses this, turning columns back into rows for detailed view.
Execution Sample
SQL
SELECT Year, Product, Sales FROM SalesData;
-- Pivot example:
SELECT Year, [A] AS ProductA, [B] AS ProductB FROM
(SELECT Year, Product, Sales FROM SalesData) src
PIVOT (SUM(Sales) FOR Product IN ([A], [B])) AS pvt;
-- Unpivot example:
SELECT Year, Product, Sales FROM
(SELECT Year, ProductA, ProductB FROM PivotedData) p
UNPIVOT (Sales FOR Product IN (ProductA, ProductB)) AS unpvt;
Shows raw sales data, then pivots product sales by year, then unpivots back to detailed rows.
Execution Table
StepActionInput DataTransformationOutput Data
1Start with raw data[{Year:2020, Product:A, Sales:100}, {Year:2020, Product:B, Sales:150}, {Year:2021, Product:A, Sales:200}, {Year:2021, Product:B, Sales:250}]NoneSame as input
2Pivot rows to columnsRaw dataGroup by Year, create columns for Product A and B with SUM(Sales)[{Year:2020, ProductA:100, ProductB:150}, {Year:2021, ProductA:200, ProductB:250}]
3Unpivot columns to rowsPivoted dataConvert ProductA and ProductB columns back to rows with Product name and Sales[{Year:2020, Product:A, Sales:100}, {Year:2020, Product:B, Sales:150}, {Year:2021, Product:A, Sales:200}, {Year:2021, Product:B, Sales:250}]
4EndUnpivoted dataNo further transformationSame as step 1 data
💡 Transformation complete: data returned to original detailed form after pivot and unpivot
Variable Tracker
VariableStartAfter PivotAfter UnpivotFinal
DataSetRaw rows with Year, Product, SalesRows grouped by Year with Product columns and summed SalesRows with Year, Product, Sales restoredSame as Start
Key Moments - 3 Insights
Why does pivot create new columns instead of rows?
Pivot aggregates data by grouping rows and turning unique values from one column into new columns, as shown in execution_table step 2.
How does unpivot restore the original row format?
Unpivot takes multiple columns and converts them back into rows with a column indicating the original column name, as seen in execution_table step 3.
Can pivot and unpivot be used on any data?
They require structured data where pivot columns and unpivot columns are known; otherwise, the transformation won't work correctly.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output data after the pivot step?
A[{Year:2020, Product:A, Sales:100}, {Year:2020, Product:B, Sales:150}]
B[{Year:2020, ProductA:100, ProductB:150}, {Year:2021, ProductA:200, ProductB:250}]
C[{Year:2020, Product:A, Sales:250}, {Year:2021, Product:B, Sales:450}]
D[{Year:2020, ProductA:250, ProductB:400}]
💡 Hint
Check execution_table row 2 under Output Data for the pivot result.
At which step does the data return to its original detailed row format?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table rows 3 and 4; unpivot happens at step 3.
If the pivot step used MAX instead of SUM, how would the output change?
AIt would show the maximum sales per product per year instead of total sales.
BIt would show the minimum sales per product per year.
CIt would not change the output.
DIt would cause an error.
💡 Hint
Pivot aggregates data; changing SUM to MAX changes aggregation behavior as in execution_table step 2.
Concept Snapshot
Pivot turns row values into columns to summarize data.
Unpivot reverses this, turning columns back into rows.
Use PIVOT with aggregation functions like SUM.
Use UNPIVOT to normalize columns into rows.
Both require knowing which columns to transform.
Full Transcript
Pivot and unpivot are SQL techniques to reshape data. Pivot converts row values into columns, often summarizing data by grouping and aggregating. Unpivot reverses this process, turning columns back into rows for detailed analysis. The execution flow starts with raw data, pivots it to a summarized form, then unpivots it back to the original detailed rows. Variables like the dataset change shape accordingly. Key moments include understanding why pivot creates columns and how unpivot restores rows. The visual quiz tests understanding of these steps and aggregation effects.

Practice

(1/5)
1. What is the main purpose of the PIVOT operation in SQL?
easy
A. To convert rows into columns for easier data summarization
B. To convert columns into rows to list data
C. To delete duplicate rows from a table
D. To join two tables based on a common column

Solution

  1. Step 1: Understand what pivot does

    PIVOT changes the orientation of data by turning row values into columns.
  2. Step 2: Compare with other options

    Only To convert rows into columns for easier data summarization correctly describes this; B describes unpivot, C and D are unrelated.
  3. Final Answer:

    To convert rows into columns for easier data summarization -> Option A
  4. Quick Check:

    Pivot = rows to columns [OK]
Hint: Pivot flips rows to columns; unpivot does the reverse [OK]
Common Mistakes:
  • Confusing pivot with unpivot
  • Thinking pivot deletes data
  • Mixing pivot with join operations
2. Which of the following is the correct syntax to unpivot columns Q1, Q2, Q3 into rows in SQL Server?
easy
A. SELECT Product, Quarter, Sales FROM SalesData UNPIVOT (Sales IN (Q1, Q2, Q3)) AS Unpvt
B. SELECT Product, Quarter, Sales FROM SalesData UNPIVOT (Sales FOR Quarter IN ([Q1], [Q2], [Q3])) AS Unpvt
C. SELECT Product, Quarter, Sales FROM SalesData UNPIVOT (Quarter FOR Sales IN (Q1, Q2, Q3)) AS Unpvt
D. SELECT Product, Quarter, Sales FROM SalesData PIVOT (Sales FOR Quarter IN (Q1, Q2, Q3)) AS Pvt

Solution

  1. Step 1: Recall UNPIVOT syntax

    UNPIVOT requires specifying the value column and the column that holds the original column names (FOR clause).
  2. Step 2: Check each option

    SELECT Product, Quarter, Sales FROM SalesData UNPIVOT (Sales FOR Quarter IN ([Q1], [Q2], [Q3])) AS Unpvt correctly uses UNPIVOT (Sales FOR Quarter IN ([Q1], [Q2], [Q3])). Others misuse PIVOT or omit FOR clause.
  3. Final Answer:

    SELECT Product, Quarter, Sales FROM SalesData UNPIVOT (Sales FOR Quarter IN ([Q1], [Q2], [Q3])) AS Unpvt -> Option B
  4. Quick Check:

    UNPIVOT syntax = SELECT Product, Quarter, Sales FROM SalesData UNPIVOT (Sales FOR Quarter IN ([Q1], [Q2], [Q3])) AS Unpvt [OK]
Hint: UNPIVOT needs 'value FOR name IN (columns)' syntax [OK]
Common Mistakes:
  • Using PIVOT instead of UNPIVOT
  • Swapping value and FOR column names
  • Omitting the FOR clause
3. Given the table Sales with columns Product, Year, Quarter, Amount, what will be the result of this query?
SELECT * FROM Sales PIVOT (SUM(Amount) FOR Quarter IN ([Q1], [Q2], [Q3], [Q4])) AS Pvt;
medium
A. An error because SUM cannot be used in PIVOT
B. A table with columns Product, Year, Quarter, Amount unchanged
C. A table with columns Product, Year, Q1, Q2, Q3, Q4 showing summed amounts per quarter
D. A table with columns Quarter, Product, Year, Amount

Solution

  1. Step 1: Understand PIVOT with aggregation

    PIVOT with SUM aggregates Amount values grouped by Product and Year, creating columns for each Quarter.
  2. Step 2: Analyze query output

    The output will have Product, Year, and one column per quarter (Q1 to Q4) with summed amounts.
  3. Final Answer:

    A table with columns Product, Year, Q1, Q2, Q3, Q4 showing summed amounts per quarter -> Option C
  4. Quick Check:

    PIVOT with SUM aggregates rows into columns [OK]
Hint: PIVOT with SUM groups and sums data into new columns [OK]
Common Mistakes:
  • Expecting original rows unchanged
  • Thinking PIVOT cannot use aggregation
  • Confusing column order in output
4. You wrote this query to unpivot sales data:
SELECT Product, Quarter, Sales FROM SalesData UNPIVOT (Sales FOR Quarter IN (Q1, Q2, Q3)) AS Unpvt;

But it returns an error. What is the likely cause?
medium
A. The FOR clause should be after the IN clause
B. UNPIVOT cannot be used with more than two columns
C. The alias 'Unpvt' is missing parentheses
D. The column names in IN clause must be enclosed in square brackets

Solution

  1. Step 1: Check syntax for column names in UNPIVOT

    In SQL Server, column names in the IN list must be enclosed in square brackets if they are identifiers like Q1, Q2, Q3.
  2. Step 2: Identify error cause

    Missing brackets cause syntax error; other options are incorrect syntax rules.
  3. Final Answer:

    The column names in IN clause must be enclosed in square brackets -> Option D
  4. Quick Check:

    Use brackets for column names in UNPIVOT IN list [OK]
Hint: Always bracket column names in UNPIVOT IN list [OK]
Common Mistakes:
  • Omitting brackets around column names
  • Misplacing FOR clause
  • Incorrect alias syntax
5. You have a table MonthlySales with columns Store, Jan, Feb, Mar representing sales per month. You want to create a report listing Store, Month, Sales rows. Which SQL approach correctly unpivots this data?
hard
A. Use UNPIVOT: SELECT Store, Month, Sales FROM MonthlySales UNPIVOT (Sales FOR Month IN ([Jan], [Feb], [Mar])) AS Unpvt;
B. Use PIVOT: SELECT Store, Month, Sales FROM MonthlySales PIVOT (SUM(Sales) FOR Month IN ([Jan], [Feb], [Mar])) AS Pvt;
C. Use JOIN to combine Jan, Feb, Mar columns into rows
D. Use GROUP BY Store, Month without unpivot

Solution

  1. Step 1: Identify the goal

    We want to transform columns Jan, Feb, Mar into rows with Month and Sales columns.
  2. Step 2: Choose correct SQL operation

    UNPIVOT converts columns into rows; Use UNPIVOT: SELECT Store, Month, Sales FROM MonthlySales UNPIVOT (Sales FOR Month IN ([Jan], [Feb], [Mar])) AS Unpvt; uses correct syntax for this.
  3. Step 3: Evaluate other options

    PIVOT aggregates rows into columns (wrong direction), JOIN is complex and unnecessary, GROUP BY alone doesn't reshape columns.
  4. Final Answer:

    Use UNPIVOT: SELECT Store, Month, Sales FROM MonthlySales UNPIVOT (Sales FOR Month IN ([Jan], [Feb], [Mar])) AS Unpvt; -> Option A
  5. Quick Check:

    Unpivot columns to rows = Use UNPIVOT: SELECT Store, Month, Sales FROM MonthlySales UNPIVOT (Sales FOR Month IN ([Jan], [Feb], [Mar])) AS Unpvt; [OK]
Hint: Unpivot columns to rows using UNPIVOT with FOR and IN [OK]
Common Mistakes:
  • Using PIVOT instead of UNPIVOT
  • Trying to reshape with GROUP BY only
  • Overcomplicating with JOINs
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard