SQL UNPIVOT Example: Master Data Transformation Easily

Unpivot, a SQL transformation function, plays a pivotal role in data manipulation, especially when dealing with contextual data. It excelente at converting columns into rows and vice versa, simplifying data analysis and offering more flexibility in querying. Let's delve into an SQL unpivot example to grasp its functionality better.

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

Before diving into the details, understand the basic syntax of unpivot: PREPIVOT(column Expression) IN ( column1 ... ) WHERE condition ORDER BY column1, ...

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

Understanding SQL Unpivot: A Basic Example

Imagine a scenario where you have a table, Emp, with Employee ID (EID), Name, and three fields representing three different months' salaries: Jan, Feb, and March. You'd like to see each employee's salary for each month instead of three different columns.

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

Here's how you'd use unpivot to achieve this:

SELECT EID, Name, Sal_Month, Salary
FROM Emp
UNPIVOT (Salary FOR Sal_Month IN (Jan, Feb, March)) AS unpivoted

SQL LIMIT Explained with Examples | Beginner SQL Tutorial
SQL LIMIT Explained with Examples | Beginner SQL Tutorial

Explaining the Above SQL Unpivot Example

The UNPIVOT clause transforms the three columns (Jan, Feb, Mar) to rows. The syntax UNPIVOT (Salary FOR Sal_Month IN (...)) AS unpivoted hoists the value from each of the columns to a row under the Salary column and changes the column name to Sal_Month.

The AS keyword is then used to define an alias, "unpivoted", to the resultant table consisting of the row-transformed data.

SQL IN A NUTSHELL
SQL IN A NUTSHELL

The Power of SQL Unpivot: Pivot and Unpivot Together

Unpivot isn't the only transformation function at your disposal in SQL. It pairs excellently with pivot, which moves data from rows to columns. Together, they're exceptionally powerful in data manipulation and rolls out handy in real-life data analytics.

Say, you have a similar table, Sales, with Product_ID, Month, and Sales. The Sales are scattered across multiple rows, one for each month. To have a single row representing total sales by product, use the following SQL code, combining UNPIVOT and PIVOT:

SQL IN NUTSHELL
SQL IN NUTSHELL

SQL Unpivot & Pivot Example: Transforming Rows to Columns

Here's how to pivot the data from rows to columns – aggregating sales by product for each month.

SQL NULLIF() Explained with Examples | Prevent Divide by Zero Errors in SQL
SQL NULLIF() Explained with Examples | Prevent Divide by Zero Errors in SQL
Data - INTERSECT in SQL keeps only the rows that appear in both result sets.  Think of it as finding the overlap between two SELECT queries.  Use it when you want to compare two lists and return only the common records.  Simple rule: Both SELECT queries must return the same number of columns, in the same order, with compatible data types.  Great for: Finding matching products Comparing customer lists Checking shared records between tables Finding common results without writing a JOIN  Save this for your SQL revision.  #SQL #SQLServer #Database #DataAnalytics #DataDrivenInsights | Facebook
Data - INTERSECT in SQL keeps only the rows that appear in both result sets. Think of it as finding the overlap between two SELECT queries. Use it when you want to compare two lists and return only the common records. Simple rule: Both SELECT queries must return the same number of columns, in the same order, with compatible data types. Great for: Finding matching products Comparing customer lists Checking shared records between tables Finding common results without writing a JOIN Save this for your SQL revision. #SQL #SQLServer #Database #DataAnalytics #DataDrivenInsights | Facebook
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
#sql #dataanalytics #powerbi #datavisualization #businessintelligence… | Vipin Chandra | 12 comments
#sql #dataanalytics #powerbi #datavisualization #businessintelligence… | Vipin Chandra | 12 comments
SQL LIKE Explained with Examples | SQL Wildcards for Beginners
SQL LIKE Explained with Examples | SQL Wildcards for Beginners
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
SQL Joins Explained 🚀 | Beginner Data Analyst SQL Guide
SQL Joins Explained 🚀 | Beginner Data Analyst SQL Guide
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 AND vs OR Explained with Examples | Beginner SQL Tutorial
SQL AND vs OR Explained with Examples | Beginner SQL Tutorial
SQL SELECT Explained with Examples | Beginner SQL Guide
SQL SELECT Explained with Examples | Beginner SQL Guide
SQL GROUP BY Explained Visually (Beginner-Friendly Guide)
SQL GROUP BY Explained Visually (Beginner-Friendly Guide)
SQL Joins Explained with Examples | Beginner SQL Guide
SQL Joins Explained with Examples | Beginner SQL Guide
SQL Aggregate Functions Cheat Sheet for Beginners
SQL Aggregate Functions Cheat Sheet for Beginners
SQL LEFT JOIN Explained with Examples | Beginner SQL Tutorial
SQL LEFT JOIN Explained with Examples | Beginner SQL Tutorial
SQL FULL OUTER JOIN Explained with Examples | Beginner SQL Tutorial
SQL FULL OUTER JOIN Explained with Examples | Beginner SQL Tutorial
CQF - SQL
CQF - SQL
SQL Aggregate Functions Made Easy 📊 | SUM, COUNT, AVG, MAX, MIN with Examples
SQL Aggregate Functions Made Easy 📊 | SUM, COUNT, AVG, MAX, MIN with Examples
SQL in 60 days
SQL in 60 days
SQL ORDER BY clause Explained for Beginners
SQL ORDER BY clause Explained for Beginners

SELECT Product_ID, SUM(Sales) as TotalSales
FROM Sales
PIVOT(SUM(Sales) FOR Month IN ([Jan], [Feb], [Mar])) AS pivoted

Remember, you can switch between pivot and unpivot based on your data requirements. Both transform data efficiently, making it easier to analyze, visualize, and draw meaningful insights.

SQL's unpivot function may pose some initial learning curve, but once mastered, it unveils a world of opportunities, especially when handling contextual data. Practice with SQL unpivot examples to foster your skills and dabble in more complex transformation tasks.

Related Articles

Is Not Null Sql Example Reddit Sql Basics Does Not Equal Sql 100 Sql Interview Questions For Application Support In Banking W3 Sql Update Jointure Sql W3school Sql Two Inner Joins Example Sql Server Meaning Sql With Nolock Example What Is Not Equal In Sql