Master SQL Pivot W3: The Ultimate Guide to Transforming Rows into Columns

Pivoting tables in SQL, a powerful database management language, can transform data from rows to columns or vice versa, turning rows into headers and columns into data. A well-known resource for learning SQL is W3Schools, offering tutorials and interactive examples. Let's dive into SQL pivot using W3Schools as our guide.

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

Before proceeding, make sure you're comfortable with SQL basics and have a database table ready for manipulation. For this article, we'll use the W3Schools 'Customers' table: 'CustomerID', 'CustomerName', 'ContactName', 'Country', and 'City'.

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

Pivoting Customers by Country

Our first task is to create a pivot table listing the number of customers by their respective countries. We'll use the 'Country' column as headers and count the customers under each country.

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

To achieve this, we'll use the 'PIVOT' clause. Here's the SQL code:

```sql SELECT Country, COUNT(*) FROM Customers GROUP BY Country; ```

Understanding the Result

Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts

This query groups the 'Customers' table by 'Country' and counts the number of customers in each country. The result is a table with 'Country' as headers and the count of customers as data.

Now, let's explore how to use the 'PIVOT' clause to create a cross-tabulation or crosstab, which is another way to express pivoting data.

Using PIVOT Clause for Cross-Tabulation

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

The 'PIVOT' clause rotates data from long to wide format. For this example, let's imagine we want to see the number of customers from each country in the 'Europe' region. Our SQL code looks like this:

```sql SELECT * FROM ( SELECT Country, Region FROM Customers ) AS source PIVOT (COUNT(CustomerID) FOR Region IN ('Europe')); ```

The 'PIVOT' clause transforms the 'Region' data into column headers, displaying the count of customers in the 'Europe' region for each country.

Pivoting Customers by City

SQL Joins Explained with Examples | Complete JOIN Cheat Sheet for Beginners
SQL Joins Explained with Examples | Complete JOIN Cheat Sheet for Beginners

Now, let's create a pivot table showing the number of customers in each 'City'. We'll use the 'City' column as headers and count the customers under each city.

Our SQL code for this task is:

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
Learn SQL just by investing 30 minutes a day within 30 Days
Learn SQL just by investing 30 minutes a day within 30 Days
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 Joins Explained 🚀 | Beginner Data Analyst SQL Guide
SQL Joins Explained 🚀 | Beginner Data Analyst SQL Guide
SQL queries don
SQL queries don
SQL IN NUTSHELL
SQL IN NUTSHELL
7 SQL QUERIES EVERY STUDENT SHOULD MASTER
7 SQL QUERIES EVERY STUDENT SHOULD MASTER
Top 20 SQL Queries for Practice | SQL Cheat Sheet for Beginners & Interviews
Top 20 SQL Queries for Practice | SQL Cheat Sheet for Beginners & Interviews
SQL Aggregate Functions Tutorial | COUNT, SUM, AVG, MIN & MAX Examples
SQL Aggregate Functions Tutorial | COUNT, SUM, AVG, MIN & MAX Examples
SQL in 60 days
SQL in 60 days
SQL ORDER BY clause Explained for Beginners
SQL ORDER BY clause Explained for Beginners
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 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
Quicksort
Quicksort
a blue and white poster with text on it
a blue and white poster with text on it
SQL RIGHT JOIN Explained with Examples | Beginner SQL Tutorial
SQL RIGHT JOIN Explained with Examples | Beginner SQL Tutorial
Cheatsheet to learn Excel, SQL, and Python at the same time.
Cheatsheet to learn Excel, SQL, and Python at the same time.
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
SQL Query Execution Order Explained | Logical Order of SQL Query Processing
SQL Query Execution Order Explained | Logical Order of SQL Query Processing
SQL Circle 💪
SQL Circle 💪

```sql SELECT City, COUNT(*) FROM Customers GROUP BY City; ```

Applying the 'UNPIVOT' Clause

SQL Server provides the 'UNPIVOT' clause to rotate data from wide to long format. Let's use it to convert the previous pivot table back to its original long format:

```sql SELECT * FROM ( SELECT City, COUNT(*) FROM Customers GROUP BY City ) AS Source(s) UNPIVOT (CustomerCount FOR City IN (City)); ```

The 'UNPIVOT' clause transforms the 'City' headers back into a column and their corresponding values into another column named 'CustomerCount'.

In SQL, pivoting data can make it easier to read and analyze, enabling you to view data in new ways. Practice these techniques with confidence, using W3Schools as your go-to learning resource. When ready, tackle more complex queries and databases, expanding your SQL skills steadily.

Related Articles

W3schools Python Tuple Exercises Basic Python Viva Questions Data Encapsulation In Python W3schools Python3 Regex Examples Python Keywords Python Docs Postgresql W3schools What Is Numpy In Python With Example Simple Python Questions For Interview Python Regular Expression Examples Jinja Python Examples