How to Unpivot in SQL: A Comprehensive Guide

Unpivoting in SQL is a powerful technique that transforms data from wide to long format. It's particularly useful when you want to convert category data into rows or when your data is stored in a way that's not easily analyzed. Let's dive into how to unpivot data in SQL using the UNPIVOT operator, which is supported by SQL Server.

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

Before we begin, ensure your SQL Server version supports the UNPIVOT operator. It was introduced in SQL Server 2005, so if you're using an older version, you might need to consider other methods or functions. Now, let's get started!

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

Understanding the UNPIVOT Operator

The UNPIVOT operator in SQL Server is the opposite of the PIVOT operator. While PIVOT converts rows into columns, UNPIVOT does the reverseโ€”it converts columns into rows. It's an efficient way to transform your data, making it more manageable and suitable for analysis.

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

Understanding the syntax of UNPIVOT is crucial. The basic syntax is as follows:

```sql SELECT * FROM ( SELECT Column1, Column2, Column3,... FROM YourTable ) AS P UNPIVOT ( Value FOR SingleColumnName IN (Column1, Column2, Column3, ...) ) AS UnpivotedTable; ```

Setting Up the UNPIVOT Operator

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

To use the UNPIVOT operator, you first need to create a subquery that includes all the columns you want to convert. In our example, we included 'Column1', 'Column2', and 'Column3'.

Once you have your subquery set up, you can specify the columns you want to unpivot into rows. In the UNPIVOT clause, replace 'Value' with the name you want to give to the new column, and replace 'SingleColumnName' with the name you want to give to the column that will hold the original column names. Then, list the columns you want to unpivot in the 'IN (...)' clause.

Unpivoting Multiple Columns

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

You can use the UNPIVOT operator to unpivot multiple columns at once. Just remember to list all the columns you want to convert in the 'IN (...)' clause. SQL Server will create a new row for each combination of values across those columns.

For example, if you have a table with columns 'Region', 'Category', and 'Sales', and you want to unpivot 'Category' and 'Sales', you would list 'Category' and 'Sales' in the 'IN (...)' clause:

```sql SELECT * FROM ( SELECT Region, Category, Sales FROM YourTable ) AS P UNPIVOT ( Value FOR SingleColumnName IN (Category, Sales) ) AS UnpivotedTable; ```

Applying UNPIVOT to Real-World Data

Convert Rows to columns using 'Pivot' in SQL  |Part - 15
Convert Rows to columns using 'Pivot' in SQL |Part - 15

Now that we've seen how to set up the UNPIVOT operator, let's apply it to a real-world example using a simple Sales table:

```sql CREATE TABLE Sales ( Region varchar(50), Q1Sales int, Q2Sales int, Q3Sales int, Q4Sales int ); ```

Unpivoting Quarterly Sales

Stop Writing Slow SQL! 12 Optimization Tips You Need
Stop Writing Slow SQL! 12 Optimization Tips You Need
7 SQL Projects for Beginners | Build a Real Data Portfolio
7 SQL Projects for Beginners | Build a Real Data Portfolio
Learn SQL Fast ๐Ÿš€ | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast ๐Ÿš€ | Beginner SQL Commands Cheat Sheet for Data Analysts
SQL Trick That Makes Dynamic Queries So Much Easier
SQL Trick That Makes Dynamic Queries So Much Easier
Learn SQL In 60 Minutes
Learn SQL In 60 Minutes
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
SQL JOINS Made Easy ๐Ÿ”— | INNER, LEFT, RIGHT & FULL JOIN with Examples
SQL JOINS Made Easy ๐Ÿ”— | INNER, LEFT, RIGHT & FULL JOIN with Examples
SQL SUBSTRING() Explained with Examples | Extract Text in SQL Server
SQL SUBSTRING() Explained with Examples | Extract Text in SQL Server
a bunch of flowers sitting on top of a table with the words learn ql commands 25
a bunch of flowers sitting on top of a table with the words learn ql commands 25
SQL UPPER() Explained with Examples | Convert Text to Uppercase in SQL
SQL UPPER() Explained with Examples | Convert Text to Uppercase in SQL
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 FULL OUTER JOIN Explained with Examples | Beginner SQL Tutorial
SQL FULL OUTER JOIN Explained with Examples | Beginner SQL Tutorial
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 LEFT() Explained with Examples | Extract Characters from the Left in SQL Server
SQL LEFT() Explained with Examples | Extract Characters from the Left in SQL Server
SQL queries don
SQL queries don
How to Think in SQL (Beginner Guide)
How to Think in SQL (Beginner Guide)
SQL IN NUTSHELL
SQL IN NUTSHELL
SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, โ€ฆ
SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, โ€ฆ
๐Ÿ’ผ 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 Tutorial: The Ultimate Beginners Guide
SQL Tutorial: The Ultimate Beginners Guide

Suppose we want to convert the quarterly sales figures (Q1Sales, Q2Sales, Q3Sales, Q4Sales) into rows. We can use the UNPIVOT operator as follows:

```sql SELECT * FROM ( SELECT Region, Q1Sales, Q2Sales, Q3Sales, Q4Sales FROM Sales ) AS P UNPIVOT ( Value FOR Quarter IN (Q1Sales, Q2Sales, Q3Sales, Q4Sales) ) AS QuarterSales; ```

This query will return a result set with columns 'Region', 'Quarter', and 'Value', making it much easier to analyze the sales data.

Unpivoting Sales and Profit

Now, let's consider an expanded Sales table that includes both sales and profit columns. We can use the UNPIVOT operator to convert both columns into rows:

```sql CREATE TABLE SalesNew ( Region varchar(50), Q1Sales int, Q1Profit int, Q2Sales int, Q2Profit int, Q3Sales int, Q3Profit int, Q4Sales int, Q4Profit int ); SELECT * FROM ( SELECT Region, Q1Sales, Q2Sales, Q3Sales, Q4Sales, Q1Profit, Q2Profit, Q3Profit, Q4Profit FROM SalesNew ) AS P UNPIVOT ( Value FOR Measure IN (Q1Sales, Q2Sales, Q3Sales, Q4Sales, Q1Profit, Q2Profit, Q3Profit, Q4Profit) ) AS SalesProfit; ```

This query returns a result set with columns 'Region', 'Measure', and 'Value', which makes it much simpler to compare sales and profit figures.

Remember, unpivoting is all about converting data from one format to another. It's an essential tool for transforming your data and making it more manageable. With practice, you'll become proficient in using the UNPIVOT operator to solve a wide range of data analysis challenges. Happy coding!

Related Articles

Oracle Sql Practice Exam How To Use Nolock In Sql Top 100 Sql Interview Questions Working With Xml In Sql Server Sql Practice Problems Free W3schools Nosql Tutorial Sql With Nolock Example Does Not Equal Sql Server Sql Interview Questions W3 School W3schools Sql Is Not Null