Master Pivot and Unpivot in SQL: The Ultimate Guide

In the realm of SQL, data manipulation and transformation often require changing the orientation of data from a wide format to a long format, or vice versa. Two powerful operations that facilitate this are PIVOT and UNPIVOT. Let's delve into these operations, their functions, and how to implement them.

SQL SERVER - Exploring PIVOT and UNPIVOT - SQL Authority with Pinal Dave
SQL SERVER - Exploring PIVOT and UNPIVOT - SQL Authority with Pinal Dave

PIVOT and UNPIVOT are particularly useful when you need to convert your data from a wide format (horizontal) to a long format (vertical), and vice versa. They allow you to transform your data in a way that's more readable, manageable, and suitable for further analysis or reporting.

the diagram shows how to use pivot in an application with multiple numbers and symbols
the diagram shows how to use pivot in an application with multiple numbers and symbols

PIVOT in SQL

PIVOT is a data transformation technique that converts your data from a flat structure, or row-based data, into a vertical, column-based structure. It aggregates data from multiple rows into a single row, making it ideal for creating crosstab or pivot table reports.

How to Pivot Your Online Business: A 3-Step Audit & Strategy Guide
How to Pivot Your Online Business: A 3-Step Audit & Strategy Guide

A basic syntax for PIVOT in SQL looks like this:

SELECT * FROM ( SELECT column, value FROM table ) AS src PIVOT ( AGGREGATE FUNCTION(arguments) FOR aggregate_column IN ([pivot_column1], [pivot_column2], ...) ) AS pvt;

PIVOT Syntax Breakdown

SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, …
SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, …

The PIVOT function takes three primary arguments: the aggregate function, the row column (or group by column), and the pivot columns. Here's a breakdown:

  • AGGREGATE FUNCTION: This is a function that aggregates or groups the data together. Common functions include SUM, AVG, COUNT, MIN, and MAX.
  • ROW COLUMN: This is the column used to create rows or rows of data in your result set.
  • PIVOT COLUMNS: These are the columns you want to use as headers in your final result set.

Example of PIVOT in SQL

10k views on how to use pivot table in excel
10k views on how to use pivot table in excel

For instance, if you have sales data in a row-based format and you want to group sales by region and product, you would use PIVOT to change the data format to a crosstab, or column-based format:

SELECT * FROM ( SELECT Region, Product, Sales FROM SalesData ) AS src PIVOT ( SUM(Sales) FOR Product IN ([ProductA], [ProductB], [ProductC]) ) AS pvt;

UNPIVOT in SQL

UNPIVOT, on the other hand, does the opposite of PIVOT. It converts data from a column-based structure into a row-based structure. This is particularly useful when you have conditional data or multiple values that you want to individual rows.

Impress Your Coworkers by Using SQL UNPIVOT!
Impress Your Coworkers by Using SQL UNPIVOT!

A basic syntax for UNPIVOT in SQL looks like this:

SELECT * FROM ( SELECT column1, column2, column3, ... FROM table ) AS src UNPIVOT ( value_column FOR value_column_name IN ([column1], [column2], [column3], ...) ) AS unpvt;

UNPIVOT Syntax Breakdown

SQL IN A NUTSHELL
SQL IN A NUTSHELL
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
SQL queries don
SQL queries don
SQL in 60 days
SQL in 60 days
7 SQL Projects for Beginners | Build a Real Data Portfolio
7 SQL Projects for Beginners | Build a Real Data Portfolio
#sql #dataanalytics #powerbi #datavisualization #businessintelligence… | Vipin Chandra | 12 comments
#sql #dataanalytics #powerbi #datavisualization #businessintelligence… | Vipin Chandra | 12 comments
Top SQL Queries Every Fresher Should Practice
Top SQL Queries Every Fresher Should Practice
SQL IN NUTSHELL
SQL IN NUTSHELL
Convert Rows to columns using 'Pivot' in SQL  |Part - 15
Convert Rows to columns using 'Pivot' in SQL |Part - 15
Master SQL for Data Analytics – Beginner to Advanced
Master SQL for Data Analytics – Beginner to Advanced
💼 Most Asked SQL Interview Question!  ❓ What’s the difference between DELETE, TRUNCATE & DROP? 🚨 One keeps structure, one resets it, one wipes it out!  👉Preparing for interview? Check the Bio for playlist link  👉 Tag a friend who needs this! 🔖save it for your prep!  👉 HackerRank Topic wise SQL practice Questions: Link in Bio  Follow for daily data insights 👇 📸 Instagram | ▶️ YouTube | 📘 Facebook  . . . . . #sqlinterview #datascience #dataanalytics #sql #interviewprep #data #database #business... Interview Prep, How To Learn Sql For Data Science, Data Analyst, Computer Coding, Data Analysis Activities, Data Science Learning, Sql Programming, Job Advice, Sql Commands
💼 Most Asked SQL Interview Question! ❓ What’s the difference between DELETE, TRUNCATE & DROP? 🚨 One keeps structure, one resets it, one wipes it out! 👉Preparing for interview? Check the Bio for playlist link 👉 Tag a friend who needs this! 🔖save it for your prep! 👉 HackerRank Topic wise SQL practice Questions: Link in Bio Follow for daily data insights 👇 📸 Instagram | ▶️ YouTube | 📘 Facebook . . . . . #sqlinterview #datascience #dataanalytics #sql #interviewprep #data #database #business... Interview Prep, How To Learn Sql For Data Science, Data Analyst, Computer Coding, Data Analysis Activities, Data Science Learning, Sql Programming, Job Advice, Sql Commands
an info poster showing the different types of web pages and how they are used to create them
an info poster showing the different types of web pages and how they are used to create them
7 SQL QUERIES EVERY STUDENT SHOULD MASTER
7 SQL QUERIES EVERY STUDENT SHOULD MASTER
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
SQL Basics Every Beginner Must Know | Database, Table, Row & Column Explained
SQL Basics Every Beginner Must Know | Database, Table, Row & Column Explained
SQL Circle 💪
SQL Circle 💪
SQL Joins Explained 🚀 | Beginner Data Analyst SQL Guide
SQL Joins Explained 🚀 | Beginner Data Analyst SQL Guide
SQL Operators - SQL Made Easy
SQL Operators - SQL Made Easy
What Is a Database in SQL? | SQL Database for Beginners
What Is a Database in SQL? | SQL Database for Beginners
SQL RIGHT() Explained with Examples | Extract Characters from the Right in SQL Server
SQL RIGHT() Explained with Examples | Extract Characters from the Right in SQL Server

The UNPIVOT function takes two primary arguments: the value column and the columns you want to unpivot or turn into rows:

  • VALUE COLUMN: This is the column that contains the data you want to convert into rows.
  • COLUMNS TO UNPIVOT: These are the columns you want to turn into rows in your final result set.

Example of UNPIVOT in SQL

For instance, if you have data in a wide format where multiple values are in different columns, you can use UNPIVOT to change the data format to a row-based format:

SELECT * FROM ( SELECT Id, Name, Score1, Score2 FROM Students ) AS src UNPIVOT ( Score FOR ScoreType IN ([Score1], [Score2]) ) AS unpvt;

Mastering PIVOT and UNPIVOT in SQL can make data manipulation and transformation significantly more efficient and intuitive. With these tools in your toolbox, you're ready to tackle even the most challenging data transformations. So, the next time you find yourself dealing with wide or long data formats, remember your friend, the SQL PIVOT or UNPIVOT.

Related Articles

How Long To Learn Sql To Get A Job Update Set Sql Example What Is Sql Academy W3schools Ascii Create Table Sql With Identity Column Update Set Sql Where Update Trigger Sql Server Example Create Table Sql With Primary Key Auto Increment Create Table Sql With Primary Key Sql Server Create Table Example