PIVOT and UNPIVOT Operator in SQL Server – C# Example Code

By: Amit Bhagwani
Updated: August 14th, 2019 | Technology: Asp.Net, ASP.NET Core, Asp.Net MVC, SQL Serve

PIVOT and UNPIVOT both are the relational operators in SQL server. These both are used to convert a table expression in SQL server. PIVOT operator is used to transfer your data row-level to columns level. Where as UNPIVOT is reverse of PIVOT function, it is used to transfer data column level to row-level in the SQL server.

PIVOT and UNPIVOT Operator in SQL Server

Insert records in the table with this script.

Now we will check data with this query, you will get the result as below image.

Output:

PIVOT and UNPIVOT operator with this SQL

Now we start understanding the PIVOT and UNPIVOT operator with this SQL table.

SQL PIVOT:

This is basically used while you processing on data in the stored procedures and functions. It is a relational operator by this, we can convert our row data into columns data. We can also do an aggregate operation on it. The PIVOT tables return the unique value of columns of the table.

Syntax:

Example:

Output:

PIVOT and UNPIVOT Operator in SQL Server

In the above result you can we have calculated the sum of the credit score for Mihir, Jigna and Harshad employees corresponding to year value.

SQL UNPIVOT

Unpivot is the reverse process of PIVOT, it converts column-level data to row-level. for an unpivot example we are going to declare one temp variable from the above Employee table.

Example:

Now we are inserting the rows into that temp variable with the below query.

Output:

PIVOT and UNPIVOT Operator in SQL Server

So this is the basic concept of PIVOT and UNPIVOT in SQL, this basically used in the store procedures while we processing on the data.

Hope you liked the example used and sample query.

Thank you for reading.