SQL Pivot Columns to Rows Example Tutorial With Step By Step Guide

In the realm of data manipulation, SQL offers a powerful tool known as pivoting to transform columns into rows and vice versa. This feature, although not built-in by default, can be achieved using conditional aggregation functions and CASE expressions. Let's explore SQL pivot columns to rows with a practical example.

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

Imagine you have a table named 'Sales' with the following structure:

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
  1. Product: The name of the product
  2. Year: The year when the sale occurred
  3. SalesAmount: The total sales amount for that product in that year

Initially, your data might look like this:

SQL ORDER BY Explained with Examples | Sort Data in SQL
SQL ORDER BY Explained with Examples | Sort Data in SQL
ProductYearSalesAmount
ProductA201810000
ProductA201912000
ProductB20188000
ProductB201915000

Creating a Pivot Table

>SQL : Multiple Row and Column Subqueries - w3resource
>SQL : Multiple Row and Column Subqueries - w3resource

A pivot table is an SQL query result that swaps rows and columns for better visualization or analysis. Let's pivot the 'SalesAmount' column from 'Sales' table to display it as distinct 'Year' rows for each 'Product'.

Using CASE Expression

The CASE expression allows us to test certain conditions and return a result accordingly. Here's how to use it for pivoting:

SQL - Select specific columns from a table
SQL - Select specific columns from a table

SQL:

```sql SELECT Product, MAX(CASE WHEN Year = 2018 THEN SalesAmount END) AS '2018', MAX(CASE WHEN Year = 2019 THEN SalesAmount END) AS '2019' FROM Sales GROUP BY Product ```

The MAX function is used with CASE expression to treat NULL values from evaluated columns. It replaces these NULLs with 0, thus correctly representing the absence of data for a particular 'Year'.

Result of the Pivoted Table

SQL ROW_NUMBER() Explained with Examples | Beginner SQL Window Function Tutorial
SQL ROW_NUMBER() Explained with Examples | Beginner SQL Window Function Tutorial

The SQL query will return the following output:

Product20182019
ProductA1000012000
ProductB800015000
SQL - Select all columns that satisfy a specific condition
SQL - Select all columns that satisfy a specific condition
SQL LAG() Explained with Examples | Beginner SQL Window Function Tutorial
SQL LAG() Explained with Examples | Beginner SQL Window Function Tutorial
SQL LIMIT Explained with Examples | Beginner SQL Tutorial
SQL LIMIT Explained with Examples | Beginner SQL Tutorial
SQL SUM() Explained with Examples | Beginner SQL Tutorial
SQL SUM() Explained with Examples | Beginner SQL Tutorial
SQL in 60 days
SQL in 60 days
Autofit Rows and Columns in Excel with VBA
Autofit Rows and Columns in Excel with VBA
a table with numbers and symbols on it that says,'s the number functions for each
a table with numbers and symbols on it that says,'s the number functions for each
SQL SELF JOIN Explained with Examples | Beginner SQL Tutorial
SQL SELF JOIN Explained with Examples | Beginner SQL Tutorial
Impress Your Coworkers by Using SQL UNPIVOT!
Impress Your Coworkers by Using SQL UNPIVOT!
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 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 MAX() Explained with Examples | Beginner SQL Tutorial
SQL MAX() Explained with Examples | Beginner SQL Tutorial
SQL Basics Every Beginner Must Know | Database, Table, Row & Column Explained
SQL Basics Every Beginner Must Know | Database, Table, Row & Column Explained
a table that has some words on it
a table that has some words on it
a blue and white poster with text on it
a blue and white poster with text on it
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
SQL GROUP BY Explained with Examples | Beginner SQL Tutorial
SQL GROUP BY Explained with Examples | Beginner SQL Tutorial
SQL AVG() Explained with Examples | Beginner SQL Tutorial
SQL AVG() Explained with Examples | Beginner SQL Tutorial
SQL CROSS JOIN Explained with Examples | Beginner SQL Tutorial
SQL CROSS JOIN Explained with Examples | Beginner SQL Tutorial

Dynamic Pivoting Using Concatenation

If your 'Year' column contains dynamic or varying values, you can use dynamic SQL and string concatenation to build the pivot query. This approach, however, requires knowledge of the database system's dynamic SQL capabilities and can be more complex to implement.

Building the Dynamic SQL

First, create a list of unique 'Year' values and use them to construct the pivot query. Then, execute the query using the 'EXEC' statement in SQL Server or 'PREPARE' and 'EXECUTE' in MySQL.

Executing the Dynamic SQL Query

The dynamic SQL query will return a similar pivoted table as the previous example but with flexible 'Year' column names.

Now that we've seen how to SQL pivot columns to rows, remember that pivoting isn't always the best approach. It largely depends on how your data is structured and how you need to present it. Regardless, being comfortable with pivoting can greatly enhance your SQL skills and give you more control over your data.

Related Articles

W3 Bootcamp Reddit What Is Max Date In Sql Sql Server Create Table Foreign Key Identity W3schools Assembly What Is Sql Essential Training Create Table Sql With Composite Primary Key Sql Pivot And Unpivot In Same Query Sql Create Table With Foreign Key With Name Sql Max Date For Each Id Pivot In Sql W3schools