Master the SQL Pivot Function: A Step-by-Step Guide

The PIVOT function in SQL is a powerful tool that allows you to rotate or transpose data in a tabular format. It's particularly useful when you want to display results in a summarized, easy-to-read manner. Here's a comprehensive guide on how to use it effectively.

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

Before diving into the examples, it's essential to understand the basic syntax. The PIVOT function has two forms: PIVOT and UNPIVOT. Here, we'll focus on the PIVOT function, which follows this general structure:

10k views on how to use pivot table in excel
10k views on how to use pivot table in excel

Understanding the PIVOT Function Syntax

The basic syntax for the PIVOT function is:

SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, …
SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, …
SELECT * FROM PIVOT(...)

where:

Excel Pivot Table Explained (Part 1) | Easy Guide for Beginners with Example
Excel Pivot Table Explained (Part 1) | Easy Guide for Beginners with Example
  • Column to Aggregate: This is the column you want to group by and pivot.
  • Column to Pivot: This is the column you want to rotate or transpose.
  • Value Column: This is the column that contains the values you want to aggregate.

Applying PIVOT to a Simple Query

Let's start with a simple example using a hypothetical 'Sales' table that has 'Category', 'Year', and 'Sales' columns.

a paper with some writing on it that says pivot function in excel
a paper with some writing on it that says pivot function in excel

Suppose we want to display sales data for each category across two years (2020 and 2021). Here's how you can do it:

SELECT Category, [2020], [2021] FROM ( SELECT Category, Year, Sales FROM Sales ) AS Ԁ PIVOT( SUM(Sales) FOR Year IN ([2020], [2021]) )AS давт

Pivoting Data by Multiple Columns

How to Update an Excel Pivot Table - Even if the Source Data Changes (+ video tutorial)
How to Update an Excel Pivot Table - Even if the Source Data Changes (+ video tutorial)

In the previous example, we pivoted data based on a single column ('Year'). However, you can also pivot data by multiple columns.

Pivoting Data by Two Columns

How to Pivot Your Online Business: A 3-Step Audit & Strategy Guide
How to Pivot Your Online Business: A 3-Step Audit & Strategy Guide
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
how to create a pivot table for data analss in microsoft excel - cover
how to create a pivot table for data analss in microsoft excel - cover
the pivot tables basics poster is shown in green and white, with text on it
the pivot tables basics poster is shown in green and white, with text on it
How to Use the Offset Function in Excel Pivot Tables?
How to Use the Offset Function in Excel Pivot Tables?
SQL Window Functions Explained with Examples | Beginner SQL Tutorial
SQL Window Functions Explained with Examples | Beginner SQL Tutorial
Oracle SQL Developer: How to transpose rows to columns using PIVOT function
Oracle SQL Developer: How to transpose rows to columns using PIVOT function
the pivot table tricks work smarter, not harder info sheet is shown in green
the pivot table tricks work smarter, not harder info sheet is shown in green
SQL SELF JOIN Explained with Examples | Beginner SQL Tutorial
SQL SELF JOIN Explained with Examples | Beginner SQL Tutorial
SQL LAG() Explained with Examples | Beginner SQL Window Function Tutorial
SQL LAG() Explained with Examples | Beginner SQL Window Function Tutorial
SQL Aggregate Functions Tutorial | COUNT, SUM, AVG, MIN & MAX Examples
SQL Aggregate Functions Tutorial | COUNT, SUM, AVG, MIN & MAX Examples
How to add data bars to pivot tables!
How to add data bars to pivot tables!
4.4K views · 335 reactions | 📊 Pivot Tables = Excel Superpower! ⚡ Stop doing manual calculations and start working smarter with these Pivot Table Tricks 🔥 ✔️ Analyze data faster ✔️ Create instant summaries ✔️ Find  | Excel Satish
4.4K views · 335 reactions | 📊 Pivot Tables = Excel Superpower! ⚡ Stop doing manual calculations and start working smarter with these Pivot Table Tricks 🔥 ✔️ Analyze data faster ✔️ Create instant summaries ✔️ Find | Excel Satish
Master Excel Like a Pro: Top Pivot Table Tips!
Master Excel Like a Pro: Top Pivot Table Tips!
a blue and white poster with the words which pivot table to use on it
a blue and white poster with the words which pivot table to use on it
Pivot Tables Made Easy 📊 | Excel & Google Sheets Beginner Guide
Pivot Tables Made Easy 📊 | Excel & Google Sheets Beginner Guide
SQL LIMIT Explained with Examples | Beginner SQL Tutorial
SQL LIMIT Explained with Examples | Beginner SQL Tutorial
SQL LEAD() Explained with Examples | Beginner SQL Window Function Tutorial
SQL LEAD() Explained with Examples | Beginner SQL Window Function Tutorial
Excel Quick Tip Power Query & Power Pivot
Excel Quick Tip Power Query & Power Pivot
Excel Trick: Pivot Tables Faster with This Shortcut
Excel Trick: Pivot Tables Faster with This Shortcut

Let's modify the previous example to pivot data by both 'Year' and 'Quarter'. We'll use the UNPIVOT function to first convert our columns into rows and then pivot them.

Here's the modified query:

SELECT Category, Quarter, [Jan], [Feb], [Mar] FROM ( SELECT Category, Quarter, Month, Sales FROM Sales ) AS Ԁ PIVOT( AVG(Sales) FOR Month IN ([Jan], [Feb], [Mar]) )AS давт

Handling NULL Values

When using the PIVOT function, you might encounter NULL values if there's no data for a specific category or year. To handle this, you can use the COALESCE function to replace NULL with zeros.

For example:

SELECT Category, [2020], [2021] FROM ( SELECT Category, Year, Sales FROM Sales ) AS Ԁ PIVOT( SUM(COALESCE(Sales, 0)) FOR Year IN ([2020], [2021]) )AS давт

Understanding and using the PIVOT function effectively can greatly enhance your SQL skills and make your reports more informative and user-friendly.

Related Articles

When To Use Alias In Sql Create Table Sql With Identity Column What Is The Maximum Date In Sql Sql Commit Example What Is Max Date In Sql Pivot Syntax For Sql Create Table Sql With Composite Primary Key Create Table Sql With Foreign Key Constraint W3schools Aside Sql Server Create Table Sql Example