Master SQL Pivot and Unpivot in Same Query for Data Transformation

SQL, a ubiquitous language in the realm of data management, often requires data transformation for meaningful interpretation. Two powerful tools at our disposal are the PIVOT and UNPIVOT operators. But can they coexist in a single SQL query? The answer is a resounding yes, and in this article, we'll demonstrate how to use them together in a coherent, performance-efficient manner.

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

PIVOT and UNPIVOT are not mutually exclusive. They serve different purposes but often complement each other. PIVOT transforms rows into columns based on given values, while UNPIVOT does the reverse, transforming columns into rows. By combining these operators, we canhandle complex data transformations, simplifying our data analysis and presentations.

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

Understanding PIVOT and UNPIVOT operators

The PIVOT operator aggregates values and converts them into columns based on category values specified in the query. It's particularly useful when we want to compare multiple categories side by side.

SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, โ€ฆ
SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, โ€ฆ

On the other hand, UNPIVOT transforms columns into rows, switching the perspective from a wide to a long format. This is especially handy when analyzing a large number of variables in a single view.

When to use PIVOT

How to write dynamic pivot query in SQL Server
How to write dynamic pivot query in SQL Server

Consider a scenario where you want to compare sales of different products in various regions. Without PIVOT, you'd have a long list of rows, making comparison challenging. With PIVOT, you can rotate this data, transforming it into a side-by-side comparison:

SELECT Region, Product, SUM(Sales) as Total_Sales FROM SalesData PIVOT(sum(Sales) FOR Product IN ('Product1', 'Product2', 'Product3')

When to use UNPIVOT

SQL queries don
SQL queries don

Imagine having a table with many variables (columns), making it hard to analyze data in a single view. UNPIVOT can convert these into rows, making it easier to compare variable values:

SELECT Variable, Value FROM SalesData UNPIVOT(for Value in (Var1, Var2, Var3)) as unpvt

Using PIVOT and UNPIVOT in the same SQL query

Top SQL Queries Every Fresher Should Practice
Top SQL Queries Every Fresher Should Practice

Now let's see how we can use these operators together. Suppose we have a table with sales data, but we want to compare not just products, but also variables like discounts and price ranges. Here's how we can do it:

First, we'll use PIVOT to compare products. Then, we'll use UNPIVOT to transform the price ranges into rows for easier analysis:

SQL in 60 days
SQL in 60 days
7 SQL QUERIES EVERY STUDENT SHOULD MASTER
7 SQL QUERIES EVERY STUDENT SHOULD MASTER
SQL Quick Notes Cheat Sheet | SQL Queries, Joins, Functions & Database Commands for Beginners
SQL Quick Notes Cheat Sheet | SQL Queries, Joins, Functions & Database Commands for Beginners
Top 20 SQL Queries for Practice | SQL Cheat Sheet for Beginners & Interviews
Top 20 SQL Queries for Practice | SQL Cheat Sheet for Beginners & Interviews
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
SQL Query Execution Order Explained | Logical Order of SQL Query Processing
SQL Query Execution Order Explained | Logical Order of SQL Query Processing
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 IN NUTSHELL
SQL IN NUTSHELL
Learn SQL Fast ๐Ÿš€ | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast ๐Ÿš€ | Beginner SQL Commands Cheat Sheet for Data Analysts
25 SQL QUERIES EVERY DEVELOPER SHOULD KNOW
25 SQL QUERIES EVERY DEVELOPER SHOULD KNOW
๐Ÿ’ผ 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
SQL Subqueries Explained with Examples | Beginner SQL Tutorial
SQL Subqueries Explained with Examples | Beginner SQL Tutorial
7 SQL Projects for Beginners | Build a Real Data Portfolio
7 SQL Projects for Beginners | Build a Real Data Portfolio
Dynamic PIVOT CLR โ€“ SQLServerCentral
Dynamic PIVOT CLR โ€“ SQLServerCentral
Learn SQL just by investing 30 minutes a day within 30 Days
Learn SQL just by investing 30 minutes a day within 30 Days
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
Stop Writing Slow SQL! 12 Optimization Tips You Need
Stop Writing Slow SQL! 12 Optimization Tips You Need
Data - INTERSECT in SQL keeps only the rows that appear in both result sets.  Think of it as finding the overlap between two SELECT queries.  Use it when you want to compare two lists and return only the common records.  Simple rule: Both SELECT queries must return the same number of columns, in the same order, with compatible data types.  Great for: Finding matching products Comparing customer lists Checking shared records between tables Finding common results without writing a JOIN  Save this for your SQL revision.  #SQL #SQLServer #Database #DataAnalytics #DataDrivenInsights | Facebook
Data - INTERSECT in SQL keeps only the rows that appear in both result sets. Think of it as finding the overlap between two SELECT queries. Use it when you want to compare two lists and return only the common records. Simple rule: Both SELECT queries must return the same number of columns, in the same order, with compatible data types. Great for: Finding matching products Comparing customer lists Checking shared records between tables Finding common results without writing a JOIN Save this for your SQL revision. #SQL #SQLServer #Database #DataAnalytics #DataDrivenInsights | Facebook
SQL Basics Every Beginner Must Know | Database, Table, Row & Column Explained
SQL Basics Every Beginner Must Know | Database, Table, Row & Column Explained

SELECT Region, Product, Variable, Value FROM ( SELECT Region, Product, Discount, PriceRange FROM SalesData ) AS src UNPIVOT(for Value in (Discount, PriceRange)) AS unpvt PIVOT(sum(Sales) FOR Product IN ('Product1', 'Product2', 'Product3'))

This query first ensures all variables (Discount and PriceRange in this case) are rows using UNPIVOT, then it uses PIVOT to transform the products into columns. The result is a clear, comparative analysis of our sales data.

Combining PIVOT and UNPIVOT: A real-life example

Let's take a practical example. Consider a retail store that wants to compare sales by region, product, and season. The 'SalesData' table has columns for 'Region', 'Product', 'Sales', and 'Season'. To compare sales by season and product, we can use the following SQL query:

SELECT Region, Season, Product, SUM(Sales) as Total_Sales FROM SalesData PIVOT(sum(Sales) FOR Product IN ('Product1', 'Product2', 'Product3'))

But what if we also want to compare the average price per product? We can use UNPIVOT to convert 'Spring', 'Summer', 'Autumn', and 'Winter' into rows, allowing us to compare seasonally:

SELECT Region, Season, Product, AVG(Price) as Average_Price FROM ( SELECT Region, Product, Season, Price FROM SalesData ) AS src UNPIVOT(for Price in (Spring, Summer, Autumn, Winter)) AS unpvt PIVOT(sum(Sales) FOR Product IN ('Product1', 'Product2', 'Product3'))

There you have it! We've just shown how to combine PIVOT and UNPIVOT in a single SQL query for comprehensive data analysis. By mastering these operators, you can handle complex data transformation easily and efficiently. Now go forth and transform your data!

Related Articles

What Is Sql Classes How To Use Trigger In Sql Server With Example Create Temp Table Sql With Values Create Table Sql With Constraints Database Trigger Sql Server Example Create Table If Not Exists Sql Server Example Sql Set Variable With Multiple Values What Is Sql Essential Training Sql Create Table Primary Key With Name Update Set Sql With Select