How to Pivot in SQL W3Schools: Master Data Transformation

When working with SQL databases, scenarios often arise where you need to retrieve data that's not displayed in your initial query results. This is where the SQL PIVOT feature comes in handy, allowing you to convert rows into columns, or vice versa. In this guide, we'll delve into the world of SQL PIVOT using examples from w3schools.

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

To begin, let's understand a simple scenario. Suppose you have an Employee table with columns 'EmployeeName', 'Department', and 'Salary'. You want to switch the 'Department' and 'EmployeeName' columns so that the departments are displayed as separate columns, with employee names and salaries within them. This is exactly what SQL PIVOT helps you achieve.

SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, …
SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, …

Pivot Syntax

The basic syntax for the PIVOT command in SQL is as follows:

SQL Quick Notes Cheat Sheet | SQL Queries, Joins, Functions & Database Commands for Beginners
SQL Quick Notes Cheat Sheet | SQL Queries, Joins, Functions & Database Commands for Beginners

SELECT columnName, [col1], [col2], ... FROM tableName PIVOT ( aggregate_function (columnName) FOR columnName IN ([col1], [col2], ...)) AS PivotTable

Understanding the Syntax

SQL ORDER BY Explained with Examples | Sort Data in SQL
SQL ORDER BY Explained with Examples | Sort Data in SQL

In the syntax above, replace 'columnName' with the name of the column you want to use as the rows. Replace '[col1]', '[col2]', etc., with the values that you want to use as columns. 'aggregate_function' refers to the function you want to apply to the data, like SUM, COUNT, AVG, etc.

The 'tableName' is the name of your table. After executing the PIVOT transformation, the resulting table is given an alias 'PivotTable'.

Example from w3schools

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

Let's use an example from w3schools. We have a table 'OrderDetails' with columns 'Product', 'Quantity', and 'Price'. We want to convert the 'Product' column into columns, with 'Quantity' and 'Price' as the values within them. The SQL query would look like this:

SELECT Product, SUM(Quantity), SUM(Price * Quantity) FROM OrderDetails PIVOT (SUM(Quantity) FOR Product IN ( 'Apple', 'Banana', 'Cherry' )) AS PivotTable

In this query, we're using the SUM aggregate function to calculate the total quantity and total cost for each product.

7 SQL Projects for Beginners | Build a Real Data Portfolio
7 SQL Projects for Beginners | Build a Real Data Portfolio

SQL Server vs MySQL PIVOT

Although the concept of PIVOT is similar in both SQL Server and MySQL, the syntax and execution may differ slightly. In MySQL, you might need to use conditional aggregation (CASE statement) or dynamic SQL to achieve the same results as the PIVOT function in SQL Server.

SQL ORDER BY clause Explained for Beginners
SQL ORDER BY clause Explained for Beginners
Learn SQL just by investing 30 minutes a day within 30 Days
Learn SQL just by investing 30 minutes a day within 30 Days
Learn SQL In 60 Minutes
Learn SQL In 60 Minutes
SQL JOINS Made Easy 🔗 | INNER, LEFT, RIGHT & FULL JOIN with Examples
SQL JOINS Made Easy 🔗 | INNER, LEFT, RIGHT & FULL JOIN with Examples
SQL SELF JOIN Explained with Examples | Beginner SQL Tutorial
SQL SELF JOIN Explained with Examples | Beginner SQL Tutorial
SQL Tutorial: The Ultimate Beginners Guide
SQL Tutorial: The Ultimate Beginners Guide
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
SQL SUBSTRING() Explained with Examples | Extract Text in SQL Server
SQL SUBSTRING() Explained with Examples | Extract Text in SQL Server
SQL LEFT() Explained with Examples | Extract Characters from the Left in SQL Server
SQL LEFT() Explained with Examples | Extract Characters from the Left in SQL Server
SQL LAG() Explained with Examples | Beginner SQL Window Function Tutorial
SQL LAG() Explained with Examples | Beginner SQL Window Function Tutorial
SQL Mindmap for Beginners & Pros 📊 | Master Queries, Joins, DDL, DML Fast
SQL Mindmap for Beginners & Pros 📊 | Master Queries, Joins, DDL, DML Fast
SQL Learning Roadmap for Beginners | Step by Step Database Guide
SQL Learning Roadmap for Beginners | Step by Step Database Guide
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
SQL NULLIF() Explained with Examples | Prevent Divide by Zero Errors in SQL
SQL NULLIF() Explained with Examples | Prevent Divide by Zero Errors in SQL
How to Think in SQL (Beginner Guide)
How to Think in SQL (Beginner Guide)
SQL REPLACE() Explained with Examples | Replace Text in SQL Server
SQL REPLACE() Explained with Examples | Replace Text 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
SQL Joins Explained with Examples | Complete JOIN Cheat Sheet for Beginners
SQL Joins Explained with Examples | Complete JOIN Cheat Sheet for Beginners
SQL JOINS Explained for Behinners
SQL JOINS Explained for Behinners
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

MySQL Example

Using the same 'OrderDetails' table, the equivalent MySQL query would be:

SELECT Product, SUM(CASE WHEN Product = 'Apple' THEN Quantity ELSE 0 END) as AppleQuant, SUM(CASE WHEN Product = 'Banana' THEN Quantity ELSE 0 END) as BananaQuant, SUM(CASE WHEN Product = 'Cherry' THEN Quantity ELSE 0 END) as CherryQuant FROM OrderDetails GROUP BY Product

In this MySQL example, we're using the CASE statement to treat the data as columns. For each product, the quantity is summed, and for products not present, it defaults to zero.

Learning to use the PIVOT function effectively can greatly enhance your data analysis capabilities in SQL. With practice, you'll find it easier to reshape your data to fit your analysis needs. Happy querying!

Related Articles

Sql Pivot And Unpivot In Same Query When To Use Alias In Sql What Is The Maximum Date In Sql Create Table Sql With Primary Key Auto Increment What Is Max Date In Sql Pivot Unpivot Sql Server Example Create Temp Table Sql Example Create Table If Not Exists Update Trigger Sql Server Example How Long To Learn Sql To Get A Job