Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Python Programs
    • Java Programs

UNPIVOT in SQL

by suresh

The Unpivot SQL is one of the most useful Operators to convert the Column names into Row values. Or say, Rotating Pivot table to regular table. Let us see how to convert Column names into Row values using Unpivot in SQL Server with example.

The below screenshot shows the data present in our [SQL Unpivot Source] table. Using this Pivot data, we will convert Column names (2011, 2012, 2013 and 2013) into Row values

Unpivot in SQL 1

UNPIVOT in SQL Example

In this Unpivot example, we will convert the Column names (2011, 12, 13, and 2014) into Row values using a built-in operator called Unpivot along with SQL IN Operator.

In this SQL example, the Product Name column values will remain the same. However, the Order Quantity rearranges a spermatozoon the Order Year.

-- Sql Server UNPIVOT Example
SELECT [Product Name]
      ,[Order Year]
      ,[Order Quantity]
FROM [SQL UnPivot Source]
UNPIVOT (
          [Order Quantity] FOR [Order Year] 
          IN ([2011],[2012],[2013],[2014]) 
	) AS [UNPIVOT TABLE]

OUTPUT

Unpivot in SQL 2

UNPIVOT Alternatives

If the interviewer is willing to test your coding skills, then you can expect this question in the interviews. Following are some of the alternative approaches to achieve the Unpivot functionality in SQL Server

Using Cross Apply Values as Unpivot alternative

In this example, we are using the Cross apply to unpivot the above-specified pivot table.

-- Sql Server UNPIVOT Alternative Example
SELECT Original.[Product Name] 
      ,Unpivoted.[Order Year]
      ,Unpivoted.[Order Quantity]     
FROM [SQL UnPivot Source] AS Original
CROSS APPLY 
 (
   VALUES 
         ([2011], '2011')
        ,([2012], '2012')
        ,([2013], '2013')
        ,([2014], '2014')
 ) Unpivoted ([Order Year], [Order Quantity] )

OUTPUT

Unpivot in SQL 3

Unpivot alternative Case Statement along with Cross Join

In this example, We are going to use Case Statement along with Cross Join to achieve the SQL Unpivot functionality

SELECT 
   Original.[Product Name],
   Unpivoted.[Order Year],
   [Order Quantity]  = 
       CASE Unpivoted.[Order Year]
          WHEN '2011' THEN Original.[2011]
          WHEN '2012' THEN Original.[2012]
          WHEN '2013' THEN Original.[2013]
          WHEN '2014' THEN Original.[2014]
       END
FROM (
       SELECT [Product Name],[2011],[2012],[2013],[2014]
       FROM [SQL UnPivot Source]
     ) AS Original
CROSS JOIN 
  (
    SELECT '2011' UNION ALL
    SELECT '2012' UNION ALL
    SELECT '2013' UNION ALL
    SELECT '2014'
  ) Unpivoted ([Order Year])

OUTPUT

Unpivot in SQL 4

The simplified version of the above mentioned code is:

-- Sql UNPIVOT Alternative Example
SELECT 
   Original.[Product Name],
   Unpivoted.[Order Year],
   [Order Quantity]  = 
       CASE Unpivoted.[Order Year]
          WHEN '2011' THEN Original.[2011]
          WHEN '2012' THEN Original.[2012]
          WHEN '2013' THEN Original.[2013]
          WHEN '2014' THEN Original.[2014]
       END
FROM (
       SELECT [Product Name],[2011],[2012],[2013],[2014]
	   FROM [SQL UnPivot Source]
     ) AS Original
CROSS JOIN 
  (
     VALUES ('2011'), ('2012'), ('2013'), ('2014')
  ) Unpivoted ([Order Year])

In this example, we used the Values keyword rather than using the old and traditional Union All

OUTPUT

Unpivot in SQL 5

Union All – Unpivot alternative

In this example, We are going to use Union All as an alternative to Unpivot. It might not be the ideal approach, but you get the point.

SELECT [Product Name], 
       [Order Quantity] = [2011], 
       [Order Year] = '2011' 
FROM [SQL UnPivot Source]
UNION ALL
SELECT [Product Name], [2012], '2012' 
FROM [SQL UnPivot Source]
UNION ALL
SELECT [Product Name], [2013], '2013' 
FROM [SQL UnPivot Source]
UNION ALL
SELECT [Product Name], [2014], '2014' 
FROM [SQL UnPivot Source]
ORDER BY [Product Name]

OUTPUT

Unpivot in SQL 6

Placed Under: SQL

  • Install SQL Server
  • Install SQL Management Studio
  • Uninstall Management Studio
  • Install AdventureWorks Database
  • SQL Management Studio Intro
  • Connect SQL with sqlcmd utility
  • SQL Attach Database
  • SQL Detach Database
  • SQL Restore Database
  • Restore Database using BAK
  • SQL Rename Database with Files
  • Get SQL Database Names
  • SQL Create Table
  • SQL Rename Table
  • SQL Alter Table
  • SQL Add Column
  • SQL Rename Column
  • Get SQL Table Names in a DB
  • Find SQL Table Dependencies
  • Rename SQL Table & Column
  • SQL Global & Local Temp Table
  • SQL Table Variable
  • SQL Derived Table
  • SQL DATALENGTH
  • SQL Data Types
  • DML, DDL, DCL & TCL Cmds
  • SQL Query Builder
  • SQL ALIAS
  • SQL SELECT Statement
  • SQL SELECT DISTINCT
  • SQL SELECT INTO Statement
  • SQL INSERT Statement
  • SQL INSERT INTO SELECT
  • SQL BULK INSERT or BCP
  • SQL UPDATE Statement
  • SQL UPDATE from SELECT
  • SQL DELETE Statement
  • SQL TRUNCATE Table
  • SQL CASE Statement
  • SQL MERGE Statement
  • SQL Subquery
  • SQL CTE
  • SQL PIVOT
  • SQL UNPIVOT
  • SQL Clauses Examples
  • SQL TOP Clause
  • SQL WHERE Clause
  • SQL ORDER BY Clause
  • SQL GROUP BY Clause
  • SQL HAVING Clause
  • SQL Primary Key
  • SQL Foreign Key
  • SQL Referential Integrity
  • SQL Check Constraint
  • SQL Unique Constraint
  • SQL Default Constraint
  • SQL Clustered Index
  • SQL Non Clustered Index
  • SQL Filtered Indexes
  • SQL COALESCE Function
  • SQL IS NOT NULL
  • SQL IS NULL Function
  • SQL ISNULL
  • SQL JOINS
  • SQL CROSS JOIN
  • SQL FULL JOIN
  • SQL SELF JOIN
  • SQL Outer Joins
  • SQL Cross Join Vs Inner Join
  • SQL LEFT JOIN
  • SQL RIGHT JOIN
  • SQL AND & OR Operators
  • SQL Arithmetic Operators
  • SQL BETWEEN Operator
  • SQL Comparison Operators
  • SQL LIKE
  • SQL EXCEPT
  • SQL EXISTS Operator
  • SQL NOT EXISTS Operator
  • SQL INTERSECT
  • SQL IN Operator
  • SQL NOT IN Operator
  • SQL UNION
  • SQL UNION ALL
  • SQL IF ELSE
  • SQL ELSE IF
  • SQL WHILE LOOP
  • SQL Nested While Loop
  • SQL BREAK Statement
  • SQL CONTINUE Statement
  • SQL GOTO Statement
  • SQL IIF Function
  • SQL CHOOSE Function
  • SQL Change Data Capture
  • SQL Table Partitioning
  • SQL Table Partition using SSMS
  • SQL TRY CATCH
  • SQL VIEWS
  • SQL User Defined Functions
  • SQL Alter User Defined Functions
  • SQL Stored Procedure Intro
  • Useful System Stored Procedures
  • SQL SELECT Stored Procedure
  • SQL INSERT Stored Procedure
  • SQL UPDATE Stored Procedure
  • Stored Procedure Return Values
  • Stored Procedure Output Params
  • Stored Procedure Input Params
  • Insert SP result into Temp Table
  • SQL Triggers Introduction
  • SQL AFTER INSERT Triggers
  • SQL AFTER UPDATE Triggers
  • SQL AFTER DELETE Triggers
  • SQL INSTEAD OF INSERT
  • SQL INSTEAD OF UPDATE
  • SQL INSTEAD OF DELETE
  • SQL STATIC CURSOR
  • SQL DYNAMIC CURSOR
  • SQL FORWARD_ONLY Cursor
  • SQL FAST_FORWARD CURSOR
  • SQL KEYSET CURSOR
  • SQL TRANSACTIONS
  • SQL Nested Transactions
  • SQL ACID Properties
  • Create SQL Windows Login
  • Create SQL Server Login
  • SQL Server Login Error
  • Create SQL Server Roles
  • SQL Maintenance Plan
  • Backup SQL Database
  • SQL Ranking Functions Intro
  • SQL RANK Function
  • SQL PERCENT_RANK Function
  • SQL DENSE_RANK Function
  • SQL NTILE Function
  • SQL ROW_NUMBER
  • SQL Aggregate Functions
  • SQL Date Functions
  • SQL Mathematical Functions
  • SQL String Functions
  • SQL CAST Function
  • SQL TRY CAST
  • SQL CONVERT
  • SQL TRY CONVERT
  • SQL PARSE Function
  • SQL TRY_PARSE Function
  • SQL Calculate Running Total
  • SQL Find Nth Highest Salary
  • SQL Reverse String
  • SQL FOR XML PATH
  • SQL FOR XML AUTO
  • SQL FOR XML RAW
  • C Tutorial
  • C# Tutorial
  • Java Tutorial
  • JavaScript Tutorial
  • Python Tutorial
  • MySQL Tutorial
  • SQL Server Tutorial
  • R Tutorial
  • Power BI Tutorial
  • Tableau Tutorial
  • SSIS Tutorial
  • SSRS Tutorial
  • Informatica Tutorial
  • Talend Tutorial
  • C Programs
  • C++ Programs
  • Java Programs
  • Python Programs
  • MDX Tutorial
  • SSAS Tutorial
  • QlikView Tutorial

Copyright © 2021 | Tutorial Gateway· All Rights Reserved by Suresh

Home | About Us | Contact Us | Privacy Policy