Master Unpivot in SQL Server W3Schools: A Step-by-Step Guide

SQL Server provides a powerful set of tools for data manipulation, and one of its most useful features is the ability to unpivot data. Unpivoting allows you to transform data from a wide format to a long format, making it easier to analyze and report on your data. In this article, we'll explore how to use the UNPIVOT function in SQL Server with guidance from W3Schools.

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

The UNPIVOT function in SQL Server is designed to convert multiple rows from a single column into multiple columns. It's particularly useful when you have data in a format that's difficult to work with, such as when it's stored in a string or a numeric column. By unpivoting your data, you can transform it into a format that's easy to sort, filter, and aggregate.

(2) Facebook Software, Engineering
(2) Facebook Software, Engineering

Understanding Unpivoting in SQL Server

Before we dive into the syntax and usage of the UNPIVOT function, let's first understand what unpivoting is and why it's useful. Unpivoting is a data transformation process that involves converting a dataset from a row-based format to a column-based format.

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

In other words, it's a way of 'unrolling' your data so that each data point is represented as a separate record. This can make it much easier to analyze and report on your data, as you can apply standard SQL functions and operators to each column individually.

Wide Format vs. Long Format Data

SQL Nested subquery - w3resource
SQL Nested subquery - w3resource

To see how unpivoting can help, let's consider a simple example. Suppose we have a table called 'Sales' with the following wide format data:


ID | Product | Quantity | Price
---+----------+----------+------
 1 | A        | 10       | 5.00
 1 | B        | 5        | 3.00
 2 | C        | 8        | 6.00
 2 | D        | 3        | 4.00

This table shows the sales for two customers (ID 1 and 2) for four different products (A, B, C, and D). However, this wide format makes it difficult to apply aggregate functions like SUM or AVG to calculate the total sales for each customer.

Transforming Data with UNPIVOT

(2) Facebook Software, Engineering
(2) Facebook Software, Engineering

To make this data easier to analyze, we can use the UNPIVOT function to transform it into a long format. Here's how you might do it:


SELECT ID,
       Product,
       Quantity,
       Price
FROM (SELECT ID, Product, Quantity, Price FROM Sales) AS Source
UNPIVOT
(
    [Value]
    FOR ProductName IN ([A], [B], [C], [D])
) AS UnPivotResult;

This query takes the original Sales table as its source and unpivots it into a long format. The resulting output looks like this:

  1. ID: 1, Product: A, Quantity: 10, Price: 5.00
  2. ID: 1, Product: B, Quantity: 5, Price: 3.00
  3. ID: 2, Product: C, Quantity: 8, Price: 6.00
  4. ID: 2, Product: D, Quantity: 3, Price: 4.00
an image of the server list for windows and mac oss servers, with different types of
an image of the server list for windows and mac oss servers, with different types of

Using UNPIVOT in More Complex Scenarios

While the previous example was relatively simple, the UNPIVOT function can also be used to transform more complex data. For instance, you might have a table that contains sales data for multiple products and multiple categories, like this:

Free SQL Database Book
Free SQL Database Book
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 UPPER() Explained with Examples | Convert Text to Uppercase in SQL
SQL UPPER() Explained with Examples | Convert Text to Uppercase in SQL
an image of a computer screen with text and numbers on the bottom right hand corner
an image of a computer screen with text and numbers on the bottom right hand corner
Search And Find All User Defined Functions / UDF In SQL Server | My Tec Bits
Search And Find All User Defined Functions / UDF In SQL Server | My Tec Bits
Data - UNPIVOT in SQL turns columns back into rows.  It is useful when your data is stored wide, but you need it in a row-based format for reporting, filtering, grouping, or analysis.  In this example:  Q1, Q2, and Q3 are separate columns.  UNPIVOT converts them into:  quarter → the label column amount → the value column  So instead of one row per region, you get one row per region and quarter.  Save this for your SQL reshaping toolkit.  #SQL #SQLServer #DataAnalytics #LearnSQL #Database #DataDrivenInsights | Facebook
Data - UNPIVOT in SQL turns columns back into rows. It is useful when your data is stored wide, but you need it in a row-based format for reporting, filtering, grouping, or analysis. In this example: Q1, Q2, and Q3 are separate columns. UNPIVOT converts them into: quarter → the label column amount → the value column So instead of one row per region, you get one row per region and quarter. Save this for your SQL reshaping toolkit. #SQL #SQLServer #DataAnalytics #LearnSQL #Database #DataDrivenInsights | Facebook
Data - UNION and UNION ALL both combine results from multiple SELECT queries — but they behave differently.  UNION removes duplicate rows. UNION ALL keeps every row, including duplicates.  Use UNION when you need a clean unique list. Use UNION ALL when duplicates matter or when performance is more important.  Small difference in syntax. Big difference in output.  Save this for your SQL revision.  #SQL #SQLServer #Database #DataAnalytics #LearnSQL #DataDrivenInsights | Facebook
Data - UNION and UNION ALL both combine results from multiple SELECT queries — but they behave differently. UNION removes duplicate rows. UNION ALL keeps every row, including duplicates. Use UNION when you need a clean unique list. Use UNION ALL when duplicates matter or when performance is more important. Small difference in syntax. Big difference in output. Save this for your SQL revision. #SQL #SQLServer #Database #DataAnalytics #LearnSQL #DataDrivenInsights | Facebook
7 SQL Projects for Beginners | Build a Real Data Portfolio
7 SQL Projects for Beginners | Build a Real Data Portfolio
Free SQL Database Book
Free SQL Database Book
an image of a blue and green logo on top of a black background with glowing lights
an image of a blue and green logo on top of a black background with glowing lights
- The Knowledge Hub
- The Knowledge Hub
Concatenate SQL Server Column Values with CONCAT()
Concatenate SQL Server Column Values with CONCAT()
Using CONCAT_WS() in SQL Server | My Tec Bits
Using CONCAT_WS() in SQL Server | My Tec Bits
Mapping SQL Server Query Results to a DataGridView in .NET
Mapping SQL Server Query Results to a DataGridView in .NET
SQL Subquery
SQL Subquery
SQL Sheatsheet! 👍
SQL Sheatsheet! 👍
Create Tables in SQL Server with T-SQL
Create Tables in SQL Server with T-SQL
Data - Anti join is a simple way to find what is missing.  In SQL, you can use LEFT JOIN with IS NULL to return rows from one table that have no matching row in another table.  Example:  Customers table → all customers Orders table → customers who ordered Anti join result → customers who have not placed any orders  The key pattern:  LEFT JOIN keeps all rows from the left table WHERE right_table.id IS NULL keeps only the unmatched rows  Useful for finding missing orders, unsold products, inactive users, or records that do not exist in another table.  Save this for your SQL problem-solving toolkit.  #SQL #SQLTips #AntiJoin #DataAnalysis #Database #DataCleaning #DataDrivenInsights | Facebook
Data - Anti join is a simple way to find what is missing. In SQL, you can use LEFT JOIN with IS NULL to return rows from one table that have no matching row in another table. Example: Customers table → all customers Orders table → customers who ordered Anti join result → customers who have not placed any orders The key pattern: LEFT JOIN keeps all rows from the left table WHERE right_table.id IS NULL keeps only the unmatched rows Useful for finding missing orders, unsold products, inactive users, or records that do not exist in another table. Save this for your SQL problem-solving toolkit. #SQL #SQLTips #AntiJoin #DataAnalysis #Database #DataCleaning #DataDrivenInsights | Facebook
an info sheet showing the different types of font and numbers for each type of text
an info sheet showing the different types of font and numbers for each type of text
an image of a diagram that shows the different types of data flow lines and how to use them
an image of a diagram that shows the different types of data flow lines and how to use them


ID | Product | Category | Quantity | Price
---+---------+----------+----------+------
 1 | A       | Fruits   | 10       | 5.00
 1 | B       | Vegetables| 5        | 3.00
 2 | C       | Fruits   | 8        | 6.00
 2 | D       | Meat     | 3        | 4.00

In this case, you might want to unpivot the data to separate the 'Category' column into its own row, like this:

  1. ID: 1, Product: A, Category: Fruits, Quantity: 10, Price: 5.00
  2. ID: 1, Product: B, Category: Vegetables, Quantity: 5, Price: 3.00
  3. ID: 2, Product: C, Category: Fruits, Quantity: 8, Price: 6.00
  4. ID: 2, Product: D, Category: Meat, Quantity: 3, Price: 4.00

To do this, you can use multiple UNPIVOT clauses, like this:


SELECT ID,
       Product,
       Category.a ProduktCategory,
       Quantity,
       Price
FROM (SELECT ID, Product, Category, Quantity, Price FROM Sales) AS Source
UNPIVOT (Category FOR CategoryName IN ([Fruits], [Vegetables], [Meat])) AS UnPivotResult;

Unpivoting with PIVOT Tables

In some cases, you might need to unpivot data that's already been pivoted. For instance, you might have a PIVOT table that looks like this:

bage> |ID | Product_A | Product_B | Product_C | Product_D | ---+-----------+-----------+-----------+----------- 1 | 10 | 5 | 0 | 0 | 2 | 0 | 0 | 8 | 3 |

To unpivot this data, you can use the following query:


SELECT ID,
       Product,
       Quantity
FROM (SELECT ID, [A], [B], [C], [D] FROM PivotTable) AS Source
UNPIVOT (Quantity FOR Product IN ([A], [B], [C], [D])) AS UnPivotResult;

This query takes the original PivotTable as its source and unpivots it into a long format, with each product name in a separate row.

Conclusion: Leveraging UNPIVOT for Data Analysis

The UNPIVOT function in SQL Server is a powerful tool for data transformation, allowing you to convert data from wide format to long format with just a few lines of code. Whether you're working with simple sales data or complex, multi-dimensional data, UNPIVOT can help make your data analysis tasks easier and more efficient.

Remember, the key to effective data analysis is having your data in the right format. With UNPIVOT, you have the power to transform your data and make it work for you, rather than working around its quirks. So, whether you're using W3Schools or any other SQL resource, understanding and using UNPIVOT effectively will greatly enhance your data analysis capabilities.

Related Articles

Sql Server Meaning Sql Query W3resource Delete Sql Query W3schools Sql Vs Nosql W3schools Sql Interview Questions W3schools With Answers Top 100 Sql Interview Questions Sql Interview Questions Interactive Sql With Nolock Example Oracle Sql Practice Exam Is W3schools Good