#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
Step 17
4 min read

Pivot / Unpivot Operations

Learn how to transform rows to columns and back.

What is PIVOT?

Before PIVOT (Vertical)
studentsubjectscore
JohnMath90
JohnEnglish85
MaryMath95
MaryEnglish88
4 rows
After PIVOT (Horizontal)
studentMathEnglish
John9085
Mary9588
2 rows

Transform rows into columns.

Before and After

Before PIVOT (Vertical)
studentsubjectscore
JohnMath90
JohnEnglish85
MaryMath95
MaryEnglish88
4 rows
After PIVOT (Horizontal)
studentMathEnglish
John9085
Mary9588
2 rows

Tables show transformation below.

PIVOT Example

Before PIVOT (Vertical)
studentsubjectscore
JohnMath90
JohnEnglish85
MaryMath95
MaryEnglish88
4 rows
After PIVOT (Horizontal)
studentMathEnglish
John9085
Mary9588
2 rows
SELECT * FROM ( SELECT student, subject, score FROM grades ) PIVOT ( MAX(score) FOR subject IN ('Math', 'English') );

UNPIVOT - Opposite

Before PIVOT (Vertical)
studentsubjectscore
JohnMath90
JohnEnglish85
MaryMath95
MaryEnglish88
4 rows
After PIVOT (Horizontal)
studentMathEnglish
John9085
Mary9588
2 rows

Columns back to rows. Useful for normalizing data.

Summary

Before PIVOT (Vertical)
studentsubjectscore
JohnMath90
JohnEnglish85
MaryMath95
MaryEnglish88
4 rows
After PIVOT (Horizontal)
studentMathEnglish
John9085
Mary9588
2 rows
  • PIVOT: Rows become columns
  • UNPIVOT: Columns become rows
  • Syntax varies by database

Finished this topic?

Mark it complete to track your progress and maintain your streak!

SkillsetMaster - AI, Web Development & Data Analytics Courses