Oracle Pivot SQL Example A Step by Step Guide

Working with Oracle databases often requires data manipulation that may not be straightforward. One such challenge is transforming data to suit report generation or data analysis needs. The Oracle PIVOT operation offers a solution to this, allowing you to convert rows to columns, or even create a new table with data in a report-friendly format. Let's dive into an example that demonstrates how to use the Oracle PIVOT operation 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 we begin, let's assume we have an orders table with the following structure and data:

Oracle SQL Cheat Sheet
Oracle SQL Cheat Sheet

```sql CREATE TABLE orders ( order_id NUMBER, order_date DATE, product_name VARCHAR2(20), quantity NUMBER, price NUMBER ); INSERT INTO orders VALUES (1, TO_DATE('2022-01-01', 'YYYY-MM-DD'), 'ProductA', 10, 50); INSERT INTO orders VALUES (1, TO_DATE('2022-01-01', 'YYYY-MM-DD'), 'ProductB', 15, 60); INSERT INTO orders VALUES (2, TO_DATE('2022-02-01', 'YYYY-MM-DD'), 'ProductA', 5, 55); ```

Using Oracle PIVOT for Simple Aggregation

Let's say we want to see the total quantity of each product ordered in one row, rather than many rows with the same product. This can be achieved using the PIVOT clause.

Oracle Architecture
Oracle Architecture

Basic PIVOT Syntax

The basic syntax for using PIVOT in Oracle SQL is:

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

```sql SELECT product_name, SUM(quantity) AS quantity, PIVOT ( SUM(quantity) FOR product_name IN ( AS , AS , ... ) ) FROM orders WHERE order_id = 1; ```

In this example, replace , , etc., with the actual product names, and , , etc., with the column names you want in the result.

Dynamic PIVOT Clause

However, hardcoding all product names is impractical for real-world usage. Thankfully, Oracle allows dynamic SQL within PIVOT using GROUP BY and COLLECT aggregators.

#oracledba #oracle19c #databaseshutdown #sql #dbacommands #learningjourney… | Prajay Kanade
#oracledba #oracle19c #databaseshutdown #sql #dbacommands #learningjourney… | Prajay Kanade

```sql SELECT * FROM ( SELECT order_id, product_name, quantity, price FROM orders ) PIVOT ( SUM(quantity) FOR product_name IN ( SELECT DISTINCT product_name FROM orders ) ); ```

The distinct product names are generated dynamically using a subquery in the PIVOT clause.

Creating a Data Mart using PIVOT

Besides basic aggregation, PIVOT can also be used to create a sales data mart, grouping data by time periods.

an info poster showing the differences between oracle and data source services in one place,
an info poster showing the differences between oracle and data source services in one place,

Creating the Data Mart

To create a data mart, we'll first create a PIVOT query and then use the result to create a permanent table.

Oracle PL/SQL Tutorial
Oracle PL/SQL Tutorial
💼 Most Asked SQL Interview Question!  ❓ What’s the difference between DELETE, TRUNCATE & DROP? 🚨 One keeps structure, one resets it, one wipes it out!  👉Preparing for interview? Check the Bio for playlist link  👉 Tag a friend who needs this! 🔖save it for your prep!  👉 HackerRank Topic wise SQL practice Questions: Link in Bio  Follow for daily data insights 👇 📸 Instagram | ▶️ YouTube | 📘 Facebook  . . . . . #sqlinterview #datascience #dataanalytics #sql #interviewprep #data #database #business... Interview Prep, How To Learn Sql For Data Science, Data Analyst, Computer Coding, Data Analysis Activities, Data Science Learning, Sql Programming, Job Advice, Sql Commands
💼 Most Asked SQL Interview Question! ❓ What’s the difference between DELETE, TRUNCATE & DROP? 🚨 One keeps structure, one resets it, one wipes it out! 👉Preparing for interview? Check the Bio for playlist link 👉 Tag a friend who needs this! 🔖save it for your prep! 👉 HackerRank Topic wise SQL practice Questions: Link in Bio Follow for daily data insights 👇 📸 Instagram | ▶️ YouTube | 📘 Facebook . . . . . #sqlinterview #datascience #dataanalytics #sql #interviewprep #data #database #business... Interview Prep, How To Learn Sql For Data Science, Data Analyst, Computer Coding, Data Analysis Activities, Data Science Learning, Sql Programming, Job Advice, Sql Commands
SQL in 60 days
SQL in 60 days
SQL ORDER BY Explained with Examples | Sort Data in SQL
SQL ORDER BY Explained with Examples | Sort Data in SQL
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
SQL
SQL LIMIT Explained with Examples | Beginner SQL Tutorial
SQL LIMIT Explained with Examples | Beginner SQL Tutorial
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 Joins Explained with Examples | Complete JOIN Cheat Sheet for Beginners
SQL Joins Explained with Examples | Complete JOIN Cheat Sheet for Beginners
(2) Facebook Software, Engineering
(2) Facebook Software, Engineering
基本SQL構文のSQLワークシート | Oracle 日本
基本SQL構文のSQLワークシート | Oracle 日本
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
SQL Roadmap for Beginners
SQL Roadmap for Beginners
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
SQL CASE WHEN Explained with Examples | Beginner SQL Tutorial
Impress Your Coworkers by Using SQL UNPIVOT!
Impress Your Coworkers by Using SQL UNPIVOT!
17 Sites for SQL Practice
17 Sites for SQL Practice
SQL Joins Explained 🚀 | Beginner Data Analyst SQL Guide
SQL Joins Explained 🚀 | Beginner Data Analyst SQL Guide
SQL CTE Explained with Examples | Common Table Expression Tutorial
SQL CTE Explained with Examples | Common Table Expression Tutorial

```sql SELECT order_date, product_name, SUM(quantity) AS quantity, PIVOT ( SUM(quantity) FOR product_date IN ( TO_DATE('2022-01-01', 'YYYY-MM-DD') AS '2022-01', TO_DATE('2022-02-01', 'YYYY-MM-DD') AS '2022-02', ... ) ) FROM orders GROUP BY order_date, product_name; ```

Again, replace '...' with more dates as necessary.

Creating a Permanent Table

The result of the above query can be inserted into a new table to create a data mart:

```sql CREATE TABLE sales_data_mart AS SELECT * FROM ( -- The PIVOT query here ); ```

The sales_data_mart table can now be used for report generation and analysis.

Mastering the PIVOT operation in Oracle SQL opens up new possibilities for data manipulation and analysis. With this powerful tool, you can transform data efficiently to suit your needs. Happy pivoting!

Related Articles

Not Equal To In Sql W3schools Regular Expression In Oracle Sql Query Top 100 Sql Interview Questions For Experienced Nosql Query W3schools Sql Practice Problems Free Unpivot In Sql Server W3schools Sql With Nolock Example How Does Unpivot Work In Sql How To Unpivot In Sql How To Use Nolock In Sql