SQL Topics
PIVOT and UNPIVOT
title: PIVOT and UNPIVOT
In the previous lesson, you learned about:
ROW_NUMBER()
RANK()
DENSE_RANK()which are used for ranking and analytical reporting.
Another powerful SQL feature used extensively in:
Business Intelligence
Reporting
Dashboards
Analyticsis:
PIVOT
UNPIVOTThese operators allow data to be transformed between:
Rows ↔ Columnsmaking reports easier to read and analyze.
What is PIVOT?
PIVOT converts:
Rows
↓
ColumnsIt rotates data from row format into column format.
Simple Definition
PIVOT transforms unique row values into separate columns.
Why is PIVOT Needed?
Suppose sales data looks like:
| Year | Quarter | Sales |
|---|---|---|
| 2024 | Q1 | 10000 |
| 2024 | Q2 | 15000 |
| 2024 | Q3 | 18000 |
| 2024 | Q4 | 20000 |
Question:
Can We Display Quarters
As Columns?Desired Output:
| Year | Q1 | Q2 | Q3 | Q4 |
|---|---|---|---|---|
| 2024 | 10000 | 15000 | 18000 | 20000 |
This is exactly what PIVOT does.
What is UNPIVOT?
UNPIVOT performs the reverse operation.
It converts:
Columns
↓
RowsSimple Definition
UNPIVOT transforms column values into row values.
Example
Input:
| Year | Q1 | Q2 | Q3 | Q4 |
|---|---|---|---|---|
| 2024 | 10000 | 15000 | 18000 | 20000 |
Output:
| Year | Quarter | Sales |
|---|---|---|
| 2024 | Q1 | 10000 |
| 2024 | Q2 | 15000 |
| 2024 | Q3 | 18000 |
| 2024 | Q4 | 20000 |
Understanding PIVOT
Normal Data:
Product
Month
SalesPivoted Data:
Product
Jan
Feb
Mar
AprEach month becomes a column.
Sample Sales Table
CREATE TABLE Sales
(
Product VARCHAR(50),
Quarter VARCHAR(10),
SalesAmount INT
);Sample Data
INSERT INTO Sales
VALUES
('Laptop','Q1',10000),
('Laptop','Q2',15000),
('Laptop','Q3',20000),
('Laptop','Q4',25000);PIVOT Syntax
SQL Server:
SELECT *
FROM
(
Source Query
)
AS SourceTable
PIVOT
(
AggregateFunction(ValueColumn)
FOR PivotColumn
IN
(
Column1,
Column2,
Column3
)
)
AS PivotTable;Understanding the Syntax
Aggregate Function
Usually:
SUM()
COUNT()
AVG()FOR
Specifies values to convert into columns.
IN
Lists resulting columns.
PIVOT Example
Output
| Product | Q1 | Q2 | Q3 | Q4 |
|---|---|---|---|---|
| Laptop | 10000 | 15000 | 20000 | 25000 |
How PIVOT Works
Input:
Laptop Q1 10000
Laptop Q2 15000
Laptop Q3 20000
Laptop Q4 25000Output:
Laptop 10000 15000 20000 25000Rows become columns.
Multiple Products Example
Input:
| Product | Quarter | Sales |
|---|---|---|
| Laptop | Q1 | 10000 |
| Laptop | Q2 | 15000 |
| Mobile | Q1 | 8000 |
| Mobile | Q2 | 12000 |
Output:
| Product | Q1 | Q2 |
|---|---|---|
| Laptop | 10000 | 15000 |
| Mobile | 8000 | 12000 |
What is UNPIVOT?
UNPIVOT reverses PIVOT.
Transforms:
Columns
↓
RowsUNPIVOT Syntax
SELECT *
FROM TableName
UNPIVOT
(
ValueColumn
FOR CategoryColumn
IN
(
Column1,
Column2,
Column3
)
)
AS UnpivotTable;Sample Pivoted Data
| Product | Q1 | Q2 | Q3 |
|---|---|---|---|
| Laptop | 10000 | 15000 | 20000 |
UNPIVOT Query
SELECT
Product,
Quarter,
SalesAmount
FROM SalesPivot
UNPIVOT
(
SalesAmount
FOR Quarter
IN
(
Q1,
Q2,
Q3
)
)
AS UnpivotResult;Output
| Product | Quarter | SalesAmount |
|---|---|---|
| Laptop | Q1 | 10000 |
| Laptop | Q2 | 15000 |
| Laptop | Q3 | 20000 |
PIVOT vs GROUP BY
GROUP BY:
Aggregates DataPIVOT:
Transforms LayoutExample:
GROUP BY Output:
| Quarter | TotalSales |
|---|---|
| Q1 | 18000 |
| Q2 | 27000 |
PIVOT Output:
| Product | Q1 | Q2 |
|---|
More report-friendly.
Dynamic PIVOT
Problem:
Unknown ColumnsExample:
New quarters added.
Instead of:
Q1
Q2
Q3
Q4hardcoding,
Dynamic SQL generates columns automatically.
This advanced topic is common in reporting systems.
Real-World Example: Sales Dashboard
Input:
Monthly Sales RecordsOutput:
Month-wise Dashboardusing PIVOT.
Real-World Example: Banking
Input:
Customer TransactionsOutput:
Month-wise Transaction SummaryReal-World Example: Payroll
Input:
Employee Salary RecordsOutput:
Employee Salary By MonthReal-World Example: University
Input:
Student MarksOutput:
Subjects As Columnsusing PIVOT.
Student Marks Example
Input:
| Student | Subject | Marks |
|---|---|---|
| Rahul | Math | 90 |
| Rahul | Science | 85 |
| Rahul | English | 88 |
Pivot Output:
| Student | Math | Science | English |
|---|---|---|---|
| Rahul | 90 | 85 | 88 |
Employee Attendance Example
Input:
| Employee | Month | Days |
|---|---|---|
| Rahul | Jan | 25 |
| Rahul | Feb | 24 |
Pivot Output:
| Employee | Jan | Feb |
|---|---|---|
| Rahul | 25 | 24 |
Advantages of PIVOT
Better Reporting
Creates dashboard-friendly output.
Easier Analysis
Improves readability.
Reduces Manual Processing
Automatic transformation.
Useful for BI Tools
Power BI, Tableau, SSRS.
Supports Aggregation
Works with SUM, COUNT, AVG.
Advantages of UNPIVOT
Normalizes Data
Converts reports back to row format.
Easier Data Processing
Useful for ETL pipelines.
Better Integration
Works with analytical systems.
Disadvantages
Complex Syntax
Harder for beginners.
Dynamic Columns Challenge
Static pivots require predefined columns.
Performance Cost
Large pivots can be expensive.
Database Differences
Syntax varies across databases.
Common Mistakes
Forgetting Aggregate Function
PIVOT requires aggregation.
Missing Columns in IN()
Output incomplete.
Confusing PIVOT with GROUP BY
They serve different purposes.
Ignoring NULL Values
Pivot results often contain NULLs.
Best Practices
Use Meaningful Column Names
Improve report readability.
Handle NULL Values
Use:
ISNULL()
COALESCE()where appropriate.
Use Dynamic PIVOT When Needed
Avoid hardcoded columns.
Test Performance
Large datasets may require optimization.
Prefer PIVOT for Reporting
Especially dashboard development.
Common Interview Questions
What is PIVOT?
A SQL operator that converts rows into columns.
What is UNPIVOT?
A SQL operator that converts columns into rows.
Is PIVOT an aggregation operation?
Yes.
It usually uses aggregate functions like SUM().
What is the opposite of PIVOT?
UNPIVOTWhere is PIVOT commonly used?
Reporting, analytics, dashboards, and BI systems.
Summary
PIVOT and UNPIVOT are advanced SQL operators used to transform data between row and column formats. They are widely used in reporting systems, dashboards, business intelligence platforms, and analytics applications.
In this lesson, you learned:
- What PIVOT is
- What UNPIVOT is
- PIVOT syntax
- UNPIVOT syntax
- Sales examples
- Student marks examples
- Dashboard reporting
- Advantages and disadvantages
- Best practices
Mastering PIVOT and UNPIVOT is important because data transformation is a fundamental requirement in reporting and analytics systems.
Next Step
Continue to the next lesson:
CASE Expression →
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for PIVOT and UNPIVOT.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this SQL topic.
Search Terms
sql, sql complete guide, sql tutorial, sql notes, complete, guide, advanced, pivot
Related SQL Topics