Master Pivot in Oracle SQL Query with Simple Examples

When it comes to querying databases, Oracle SQL offers a wide array of functions to extract, manipulate, and analyze data. One of these powerful features is the ability to pivot your data, transforming it from rows into columns, or vice versa. This can help you visualize and compare data in a more readable and manageable format. Let's dive into the world of pivoting in Oracle SQL with some practical examples.

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

Oracle SQL provides the SQL functions PIVOT and UNPIVOT to facilitate these transformations. While they serve the same purpose, their syntax differs slightly. In this article, we will explore both, along with their syntax and usage, providing hands-on examples for each.

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

Oracle SQL Pivot

The PIVOT function rotates your data from columns into rows, making it easier to calculate and aggregate.

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

Syntax: `SELECT column, aggregate_function(column_value) FROM table pivoting PIVOT (aggregate_function(column_value) FOR column IN (column1, column2, ...)) OVER (partitions)`

Example: Pivoting years into columns

Oracle SQL Cheat Sheet
Oracle SQL Cheat Sheet

Consider a table named `sales` with the following data:

Year | Region | Sales
---- | ------ | -----
 2020 | South  |    50
 2020 | North  |   150
 2021 | South  |    80
 2021 | North  |   200

To pivot the 'Year' column into columns, you can use the following query:

SELECT Region, SUM(CASE Year WHEN 2020 THEN Sales ELSE NULL END) AS "2020 Sales",
       SUM(CASE Year WHEN 2021 THEN Sales ELSE NULL END) AS "2021 Sales"
FROM sales
GROUP BY Region;

Example: Pivoting regions into columns

Top 20 SQL Queries for Practice | SQL Cheat Sheet for Beginners & Interviews
Top 20 SQL Queries for Practice | SQL Cheat Sheet for Beginners & Interviews

Now, let's pivot the 'Region' column instead. We'll use the PIVOT function this time:

SELECT Year, SUM(Sales) State
FROM sales
PIVOT (SUM(Sales) FOR Region IN ('South', 'North'));

Oracle SQL Unpivot

The UNPIVOT function does the opposite - it takes row data and rotates it into columns.

SQL Query Execution Order Explained | Logical Order of SQL Query Processing
SQL Query Execution Order Explained | Logical Order of SQL Query Processing

Syntax: `SELECT column FROM table unpivoting UNPIVOT (column_value FOR column IN (column1, column2, ...)) OVER (partitions)`

Example: Unpivoting columns into rows

SQL in 60 days
SQL in 60 days
SQL queries don
SQL queries don
SQL Query Execution Order
SQL Query Execution Order
25 SQL QUERIES EVERY DEVELOPER SHOULD KNOW
25 SQL QUERIES EVERY DEVELOPER SHOULD KNOW
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast 🚀 | Beginner SQL Commands Cheat Sheet for Data Analysts
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
(2) Facebook Software, Engineering
(2) Facebook Software, Engineering
SQL Basics Tutorial for Beginners – Structured Query Language Commands, Syntax & Examples Guide
SQL Basics Tutorial for Beginners – Structured Query Language Commands, Syntax & Examples Guide
SQL LEFT JOIN Explained with Examples | Beginner SQL Tutorial
SQL LEFT JOIN Explained with Examples | Beginner SQL Tutorial
the top 10 sol queries to master windows functions for each employee in their department
the top 10 sol queries to master windows functions for each employee in their department
SQL Cheat Sheet in 60 seconds 👇
SQL Cheat Sheet in 60 seconds 👇
SQL Window Functions Explained with Examples | Beginner SQL Tutorial
SQL Window Functions Explained with Examples | Beginner SQL Tutorial
7 SQL Projects for Beginners | Build a Real Data Portfolio
7 SQL Projects for Beginners | Build a Real Data Portfolio
基本SQL構文のSQLワークシート | Oracle 日本
基本SQL構文のSQLワークシート | Oracle 日本
SQL NULLIF() Explained with Examples | Prevent Divide by Zero Errors in SQL
SQL NULLIF() Explained with Examples | Prevent Divide by Zero Errors in SQL
Stop Writing Slow SQL! 12 Optimization Tips You Need
Stop Writing Slow SQL! 12 Optimization Tips You Need
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
three white containers with the words oracle and mysql on them, in front of
three white containers with the words oracle and mysql on them, in front of
Data - INTERSECT in SQL keeps only the rows that appear in both result sets.  Think of it as finding the overlap between two SELECT queries.  Use it when you want to compare two lists and return only the common records.  Simple rule: Both SELECT queries must return the same number of columns, in the same order, with compatible data types.  Great for: Finding matching products Comparing customer lists Checking shared records between tables Finding common results without writing a JOIN  Save this for your SQL revision.  #SQL #SQLServer #Database #DataAnalytics #DataDrivenInsights | Facebook
Data - INTERSECT in SQL keeps only the rows that appear in both result sets. Think of it as finding the overlap between two SELECT queries. Use it when you want to compare two lists and return only the common records. Simple rule: Both SELECT queries must return the same number of columns, in the same order, with compatible data types. Great for: Finding matching products Comparing customer lists Checking shared records between tables Finding common results without writing a JOIN Save this for your SQL revision. #SQL #SQLServer #Database #DataAnalytics #DataDrivenInsights | Facebook

Let's start with a different table, `grades`, that stores student grades in multiple subjects as columns:

Student | Math   | Science | History
--------|--------|---------|---------
 Alice  |     90 |       85 |      95
 Bob    |     80 |       75 |      85

To unpivot these columns into rows, you can use the following query:

SELECT Student, Subject, Grade
FROM grades
UNPIVOT (Grade FOR Subject IN ('Math', 'Science', 'History'));

Related Articles

Sql Vs Nosql W3schools Sql With Nolock Example Sql Not Equal To W3 Working With Xml In Sql Server Update Sql Query W3schools Duplicate Records In Sql Query W3schools Top 100 Sql Interview Questions For Experienced Sql Practice Problems Free W3 Sql Update How To Use Pivot In Oracle Sql