Learn how to use Pivot in SQL and Unpivot in SQL. Pivot and Unpivot in SQL are two relational operators that are used to convert a table expression into another. Pivot in SQL is used when we want to transfer data from the row level to the column level and Unpivot in SQL is used when we want to convert data from the column level to the row level. PIVOT and UNPIVOT relational operators are used to generate multidimensional reporting.
In this article, we will discuss both Pivot and Unpivot operators in a SQL Server database and how to create interactive tables that quickly combine and compares a large amount of data.
Firstly, we will create a table and insert some data into the table. You may use your own database tables.
Here is the Employee table query.
CREATE TABLE Employee
(
Name [nvarchar](max),
[Year] [int] ,
Sales [int]
)Insert the following data into the table.
INSERT INTO Employee
SELECT 'Pankaj',2010,72500 UNION ALL
SELECT 'Rahul',2010,60500 UNION ALL
SELECT 'Sandeep',2010,52000 UNION ALL
SELECT 'Pankaj',2011,45000 UNION ALL
SELECT 'Sandeep',2011,82500 UNION ALL
SELECT 'Rahul',2011,35600 UNION ALL
SELECT 'Pankaj',2012,32500 UNION ALL
SELECT 'Pankaj',2010,20500 UNION ALL
SELECT 'Rahul',2011,200500 UNION ALL
SELECT 'Sandeep',2010,32000Now we check the data of the Employee table.
Output

We use the above Employee table for PIVOT and UNPIVOT relational operator examples.
PIVOT in SQL
PIVOT relational operator converts data from row level to column level. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output. Using the PIVOT operator, we can perform an aggregate operations where we need them.
Syntax
SELECT <non-pivoted column>,
<list of pivoted column>
FROM
(<SELECT query to produces the data>)
AS <alias name>
PIVOT
(
<aggregation function>(<column name>)
FOR
[<column name that become column headers>]
IN ( [list of pivoted columns])
) AS <alias name for pivot table>Let us take some examples.
Example 1
SELECT [Year], Pankaj,Rahul,Sandeep FROM
(SELECT Name, [Year] , Sales FROM Employee )Tab1
PIVOT
(
SUM(Sales) FOR Name IN (Pankaj,Rahul,Sandeep)) AS Tab2
ORDER BY [Tab2].[Year]Output

In the above query, we calculated the sum of sales for Pankaj, Rahul, and Sandeep employees corresponding to the year values.
Example 2
Here is another example:
SELECT Name, 2010,2011,2012 FROM
(SELECT Name, [Year] , Sales FROM Employee )Tab1
PIVOT
(
SUM(Sales) FOR [Year] IN (2010,2011,2012)) AS Tab2
ORDER BY Tab2.NameOutput

When we execute the above query, SQL Server throws an error because we can’t provide an integer value as a column name directly. To remove this error use the brackets before each integer value as in the following code snippet:
SELECT Name, [2010],[2011],[2012] FROM
(SELECT Name, [Year] , Sales FROM Employee )Tab1
PIVOT
(
SUM(Sales) FOR [Year] IN ([2010],[2011],[2012])) AS Tab2
ORDER BY Tab2.NameOutput

Example 3
In the previous examples, we wrote the name of pivot columns. This approach is useful if we know all possible values for pivot columns. But what if the number of columns changes in the database?
Let us take the previous example. In the previous example, we used 2010, 2011, and 2012 as pivot columns. But it is not fixed that this column will not change in the future. What happens when we get data from the year 2013? 2014? or even more?
To solve this problem, we need to use dynamic queries.
First, we retrieve all unique values from a pivot column and after that, we will write a dynamic query to execute it with a pivot query at run time.
Now we can execute example 2, but using the dynamic query.
/*Declare Variable*/
DECLARE @Pivot_Column [nvarchar](max);
DECLARE @Query [nvarchar](max);
/*Select Pivot Column*/
SELECT @Pivot_Column= COALESCE(@Pivot_Column+',','')+ QUOTENAME(Year) FROM
(SELECT DISTINCT [Year] FROM Employee)Tab
/*Create Dynamic Query*/
SELECT @Query='SELECT Name, '+@Pivot_Column+'FROM
(SELECT Name, [Year] , Sales FROM Employee )Tab1
PIVOT
(
SUM(Sales) FOR [Year] IN ('+@Pivot_Column+')) AS Tab2
ORDER BY Tab2.Name'
/*Execute Query*/
EXEC sp_executesql @QueryOutput

UNPIVOT in SQL
UNPIVOT relational operator is the reverse process of the PIVOT relational operator. UNPIVOT relational operator converts data from the column level to the row level.
Example 4
Suppose the output of example 2 is stored in a Temp variable. Now we want to rotate column identifiers Pankaj, Sandeep, and Rahul into row values. For this, we use the UNPIVOT relational operator.
Declare Temp Variable
DECLARE @Tab TABLE
(
[Year] int,
Pankaj int,
Rahul int,
Sandeep int
)Insert Value in Temp Variable
INSERT INTO @Tab
SELECT [Year], Pankaj,Rahul,Sandeep FROM
(SELECT Name, [Year] , Sales FROM Employee )Tab1
PIVOT
(
SUM(Sales) FOR Name IN (Pankaj,Rahul,Sandeep)) AS Tab2
ORDER BY [Tab2].[Year]Perform UNPIVOT Operation
SELECT Name,[Year] , Sales FROM @Tab t
UNPIVOT
(
Sales FOR Name IN (Pankaj,Rahul,Sandeep)
) AS TAb2Output

We can perform the first PIVOT operation and after that UNPIVOT operation on the same table in a single query as in the following code snippet.
SELECT Name,[Year] , Sales FROM
(
SELECT [Year], Pankaj,Rahul,Sandeep FROM
(SELECT Name, [Year] , Sales FROM Employee )Tab1
PIVOT
(
SUM(Sales) FOR Name IN (Pankaj,Rahul,Sandeep)) AS Tab2
)Tab
UNPIVOT
(
Sales FOR Name IN (Pankaj,Rahul,Sandeep)
) AS TAb2Output

Note
UNPIVOT operation is a reverse process of PIVOT operation, but UNPIVOT is not the exact reverse of PIVOT. If PIVOT performs an aggregation and merges multiple rows into a single row in the output, then UNPIVOT can’t reproduce the original table-valued expression result because rows have been merged. So the conclusion is that if the PIVOT operation merges multiple rows in a single row, then UNPIVOT operation can’t retrieve the original table from the output of the PIVOT operation. But if the PIVOT operation doesn’t merge multiple rows in a single row, then UNPIVOT operation can retrieve the original table from the output of the PIVOT operation.
Let us take an example,
Case 1. PIVOT merges multiple rows

Now we perform PIVOT and UNPIVOT operations for this table and compare the resultant table from this table.
SELECT Name,[Year] , Sales FROM
(
SELECT [Year], Pankaj,Rahul,Sandeep FROM
(SELECT Name, [Year] , Sales FROM Employee )Tab1
PIVOT
(
SUM(Sales) FOR Name IN (Pankaj,Rahul,Sandeep)) AS Tab2
)Tab
UNPIVOT
(
Sales FOR Name IN (Pankaj,Rahul,Sandeep)
) AS TAb2Output

We can see that both the tables are not the same. The first table contains 10 rows but the above table contains 7 rows only. This difference occurs due to the PIVOT operation. PIVOT operation merges (4,7,8) rows in a single row and merges (3,5) rows in a single row. That's why the UNPIVOT operation can’t retrieve the original table.
Case 2. PIVOT doesn’t merge multiple rows

Now let's perform PIVOT and UNPIVOT operations for this table and compare the result of the new table with this table.
SELECT Name,[Year] , Sales FROM
(
SELECT [Year], Pankaj,Rahul,Sandeep FROM
(SELECT Name, [Year] , Sales FROM Employee )Tab1
PIVOT
(
SUM(Sales) FOR Name IN (Pankaj,Rahul,Sandeep)) AS Tab2
)Tab
UNPIVOT
(
Sales FOR Name IN (Pankaj,Rahul,Sandeep)
) AS TAb2Output

We can see that both the tables are the same.
Conclusion
Today, we learned about SQL PIVOT and UNPIVOT relational operators and learned how to convert a table expression into another. We should remember that UNPIVOT operation is the reverse process of PIVOT operation, but UNPIVOT is not the exact reverse of PIVOT.
Are you ready to supercharge your database? With Pivot in SQL Server, you can take your data to the next level. Pivot offers fast and efficient ways to query and manipulate data, allowing you to make decisions quickly and accurately. By mastering Pivot, you'll gain the skills to efficiently manage and analyze data, giving you the power to make smarter, data-driven decisions. So what are you waiting for? Take the plunge and unlock the potential of Pivot in SQL Server today!


TomasPosted Nov 12, 2024, 3:13 PM EST
Great explanation on both PIVOT and UNPIVOT in SQL Server! For those interested in going deeper into pivot transformations for data reporting, I recently covered additional techniques and best practices in my blog post here: https://finalexception.com/how-to-pivot-data-in-sql-server-for-efficient-data-reporting/
Vineet KumarPosted Jun 6, 2022, 11:31 PM EDT
Great stuff on Pivot.
gk gkPosted Oct 22, 2021, 4:55 AM EDT
Why tab used here
Ian KodePosted Oct 15, 2020, 1:04 PM EDT
If you really knew TSQL you would not use multiple UNION clauses but multiple VALUES('Dick', 2020, 123),('Joe',2019,456) etc !
Dipa MehtaPosted Mar 7, 2020, 2:36 AM EST
Interesting stuff on a pivot with SQL Server.
Arvind KumarPosted Jun 14, 2019, 10:23 PM EDT
Thanks Dude
Hein HtunPosted Mar 6, 2019, 4:20 PM EST
Thanks, bro. It helps me a lot.
jay singhPosted May 15, 2018, 3:00 AM EDT
How to implement join in dynamic query plz help
Haribansh Kumar AgrawalPosted Jan 25, 2018, 12:06 AM EST
Nice article. never thought Pivoting was so Easy
Santhakumar MunuswamyPosted Sep 17, 2015, 6:45 AM EDT
Thanks for nice article:)
Pankaj Kumar ChoudharyTOP 100Posted Sep 14, 2015, 5:50 PM EDT
Thanks Humayun Kabir Mamun Sir..........
Pankaj Kumar ChoudharyTOP 100Posted Sep 14, 2015, 5:49 PM EDT
Thanks Yashwant Vishwakarma Sir..........
Pankaj Kumar ChoudharyTOP 100Posted Sep 14, 2015, 5:49 PM EDT
Thanks Ajeet sir.........
Pankaj Kumar ChoudharyTOP 100Posted Sep 14, 2015, 5:49 PM EDT
Thanks Raja Prs
Pankaj Kumar ChoudharyTOP 100Posted Sep 14, 2015, 5:48 PM EDT
Thanks Harshad Pansuriya Sir............
Pankaj Kumar ChoudharyTOP 100Posted Sep 14, 2015, 5:48 PM EDT
Thanks Saineshwar Bageri Sir...........
Pankaj Kumar ChoudharyTOP 100Posted Sep 14, 2015, 5:48 PM EDT
Thanks Karthikeyan K Sir......... .
Pankaj Kumar ChoudharyTOP 100Posted Sep 14, 2015, 5:47 PM EDT
Thanks Shashangka Sir.......
Humayun Kabir MamunPosted Sep 14, 2015, 4:37 AM EDT
Nice...
Yashwant VishwakarmaPosted Sep 14, 2015, 3:00 AM EDT
Nice information !!!
Ajeet MishraPosted Sep 13, 2015, 11:48 PM EDT
nice
Raja TPosted Sep 13, 2015, 8:28 PM EDT
Very Nice Thanks For sharing
Harshad PansuriyaPosted Sep 13, 2015, 8:27 PM EDT
Nice One
Saineshwar BageriPosted Sep 13, 2015, 7:51 PM EDT
Good One
Karthikeyan KPosted Sep 13, 2015, 8:49 AM EDT
Good one bro :) Thanks for sharing
Shashangka ShekharPosted Sep 13, 2015, 7:59 AM EDT
Nice Share.
Pankaj Kumar ChoudharyTOP 100Posted Sep 13, 2015, 7:06 AM EDT
Thanks Upendra Pratap Shahi Sir .............
Pankaj Kumar ChoudharyTOP 100Posted Sep 13, 2015, 7:03 AM EDT
Thanks manas............
Pankaj Kumar ChoudharyTOP 100Posted Sep 13, 2015, 7:03 AM EDT
Thanks Rajeesh Menoth Sir.........
Pankaj Kumar ChoudharyTOP 100Posted Sep 13, 2015, 7:03 AM EDT
Thanks lalit kumar Sir..........
Upendra Pratap ShahiPosted Sep 13, 2015, 5:03 AM EDT
nice article pankaj......Shandar Jabrdast Jindabad...
Manas MohapatraPosted Sep 13, 2015, 2:59 AM EDT
Nice Share..
Rajeesh MenothPosted Sep 13, 2015, 2:54 AM EDT
Nice one
Lalit KumarPosted Sep 13, 2015, 12:10 AM EDT
Nice post.