Simple SQL Pivot Example Guide for Beginners

When working with data in SQL, you often find yourself in situations where you need to consolidate and present data in a specific format. A SQL pivot is a powerful tool that allows you to transform your data from a row-based orientation to a column-based orientation, making it easier to analyze and present. Let's dive into an example of a simple SQL pivot using a basic table.

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

For this example, let's consider a simple `Sales` table with the following data:

SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, …
SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, …
Product SalesRegion SalesAmount
ProductA West 1000
ProductB East 1200
ProductA East 800
ProductB West 1500

Pivot Table Syntax

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

The basic syntax for a SQL pivot is:

SELECT * FROM (SELECT column1, column2, value.column FROM table) AS PivotTable PIVOT (SUM(column2) FOR column1 IN ('value1', 'value2', ... )) AS PivotResult;

However, syntax can vary slightly based on the SQL variant you're using. For this example, we'll use MySQL, which has a simpler syntax.

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

Simple SQL Pivot Example

Let's pivot the `Sales` table to show total `SalesAmount` by `Product` for each `SalesRegion`. Here's how you can do it in MySQL:

SELECT * FROM (SELECT Product, SalesRegion, SalesAmount FROM Sales) AS PivotTable PIVOT (SUM(SalesAmount) FOR SalesRegion IN ('West', 'East')) AS PivotResult;

This query will return the following result:

Impress Your Coworkers by Using SQL UNPIVOT!
Impress Your Coworkers by Using SQL UNPIVOT!
Product West East
ProductA 1000 800
ProductB 1500 1200

Using Dynamic SQL for Pivot

In many cases, you might not know the values you're pivoting in advance. In such situations, you can use dynamic SQL to create your pivot query. Here's an example:

Excel Pivot Table Explained (Part 1) | Easy Guide for Beginners with Example
Excel Pivot Table Explained (Part 1) | Easy Guide for Beginners with Example

SET @ProductList = (SELECT GROUP_CONCAT(DISTINCT Product SEPARATOR ',') FROM Sales); SET @DynamicSQL = CONCAT('SELECT * FROM (SELECT Product, SalesRegion, SalesAmount FROM Sales) AS PivotTable PIVOT (SUM(SalesAmount) FOR SalesRegion IN (', @ProductList, ')) AS PivotResult;'); PREPARE stmt FROM @DynamicSQL; EXECUTE stmt; DEALLOCATE PREPARE stmt;

This dynamic SQL will create a pivot query using the distinct `Product` values from your `Sales` table.

Pivoted Data Analysis

SQL SUM() Explained with Examples | Beginner SQL Tutorial
SQL SUM() Explained with Examples | Beginner SQL Tutorial
SQL CTE Explained with Examples | Common Table Expression Tutorial
SQL CTE Explained with Examples | Common Table Expression Tutorial
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
SQL LEFT JOIN Explained with Examples | Beginner SQL Tutorial
SQL LEFT JOIN Explained with Examples | Beginner SQL Tutorial
SQL ORDER BY clause Explained for Beginners
SQL ORDER BY clause Explained for Beginners
SQL AVG() Explained with Examples | Beginner SQL Tutorial
SQL AVG() Explained with Examples | Beginner SQL Tutorial
SQL Window Functions Explained with Examples | Beginner SQL Tutorial
SQL Window Functions Explained with Examples | Beginner SQL Tutorial
SQL Aggregate Functions Cheat Sheet for Beginners
SQL Aggregate Functions Cheat Sheet for Beginners
SQL LAG() Explained with Examples | Beginner SQL Window Function Tutorial
SQL LAG() Explained with Examples | Beginner SQL Window Function Tutorial
SQL ROW_NUMBER() Explained with Examples | Beginner SQL Window Function Tutorial
SQL ROW_NUMBER() Explained with Examples | Beginner SQL Window Function Tutorial
SQL LEAD() Explained with Examples | Beginner SQL Window Function Tutorial
SQL LEAD() Explained with Examples | Beginner SQL Window Function Tutorial
SQL Cheat Sheet for Beginners
SQL Cheat Sheet for Beginners
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
SQL IN A NUTSHELL
SQL IN A NUTSHELL
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
SQL Basics Made Easy 💻 | SELECT, WHERE & ORDER BY with Examples
SQL Basics Made Easy 💻 | SELECT, WHERE & ORDER BY with Examples
an info poster showing the different types of web pages and how they are used to create them
an info poster showing the different types of web pages and how they are used to create them
SQL RANK() Explained with Examples | Beginner SQL Window Function Tutorial
SQL RANK() Explained with Examples | Beginner SQL Window Function Tutorial
7 SQL Projects for Beginners | Build a Real Data Portfolio
7 SQL Projects for Beginners | Build a Real Data Portfolio

Once you've created your pivot, you can use it to analyze your data in a more straightforward manner. For example, you can quickly compare sales performance between different regions for each product. From this, you might identify opportunities to improve sales in specific regions or products.

Calculating Total Sales Across All Regions

You can also compute the total sales for each product by adding the column values together:

SELECT Product, SUM(West) + SUM(East) AS Total FROM PivotResult GROUP BY Product;

This will give you a final result set showing the total sales amount for each product across all regions.

In conclusion, learning to use SQL pivots is a valuable skill that can help you present and analyze data more effectively. By leveraging the power of SQL, you can effortlessly transform your data from rows to columns, unlocking new insights and simplifying your data analysis process. Happy pivoting!

Related Articles

Types Of Sql Explained How Many Days It Take To Learn Sql Pivot Table Sql Server Example Create Table Sql With Values Create Table Sql With Composite Primary Key Create Table Sql With Foreign Key Constraint What Is Sql Academy What Is Sql Beginner Types Of Sql T Sql Pivot And Unpivot Sql Server