Mastering How to Use Pivot in Oracle SQL: A Complete Guide

The PIVOT function in Oracle SQL is an incredibly powerful tool that enables you to convert rows into columns or vice versa, , helping you restructuring your data to fit specific reporting or presentation needs. Today, we're diving in to explore how to use PIVOT effectively in Oracle SQL.

Oracle / PLSQL: PIVOT Clause
Oracle / PLSQL: PIVOT Clause

Before we delve into the details, let's ensure we're on the same page about what PIVOT does. Imagine you have a table with multiple rows of data, and each row has a unique category. The PIVOT function can transform your table so that each category has its own column, allowing you to see comparisons more clearly.

Oracle SQL Developer: How to transpose rows to columns using PIVOT function
Oracle SQL Developer: How to transpose rows to columns using PIVOT function

Understanding PIVOT's Syntax and Components

To use the PIVOT function, you'll need to understand its syntax and how its components work together. Here's the basic format:

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

PIVOT (function-name (argument-list) FOR category-column IN (category1 AS alias1, category2 AS alias2, ...)).

Function and Argument List

SQL NULLIF() Explained with Examples | Prevent Divide by Zero Errors in SQL
SQL NULLIF() Explained with Examples | Prevent Divide by Zero Errors in SQL

The function is what you want to apply to the data in each category. You can use COUNT, SUM, AVG, MIN, MAX, or even a custom function. The argument list determines which data the function should operate on.

For instance, if your function is COUNT, there's no argument needed. But if you use SUM, you might want to sum up a particular column like SUM(KNOWLEDGE_SCORE).

Category Column

an info poster showing the different features of oracle's ql - performance software
an info poster showing the different features of oracle's ql - performance software

The category column is the one that contains the data you're going to transform. This is typically a column that has unique values (each row should have a distinct value here).

For example, in a table of student scores, the category could be STUDENT_NAME, as each student is unique, or SUPERVISOR, if you wanted to group data based on who supervised each project.

Steps to Use PIVOT: A Practical Example

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

Now that we've discussed the theory, let's put it into practice. Suppose you have a table, SCORES, and you want to see the total score for each student in a single row, with a column for each subject they took:

```sql SELECT * FROM (SELECT STU_ID, SUBJECT, SCORE FROM SCORES) PIVOT( SUM(SCORE) FOR SUBJECT IN (ENG AS english, MATH AS math, SCI AS science) ) ```

In this query, we're asking for each student ID (STU_ID), summing their scores (SUM(SCORE)) for each subject, and renaming those subjects as "english", "math", and "science".

SQL CONCAT() Explained with Examples | Combine Strings in SQL Server
SQL CONCAT() Explained with Examples | Combine Strings in SQL Server
SQL TRIM() Explained with Examples | Remove Extra Spaces in SQL
SQL TRIM() Explained with Examples | Remove Extra Spaces in SQL
SQL LEAD() Explained with Examples | Beginner SQL Window Function Tutorial
SQL LEAD() Explained with Examples | Beginner SQL Window Function Tutorial
SQL in 60 days
SQL in 60 days
SQL REPLACE() Explained with Examples | Replace Text in SQL Server
SQL REPLACE() Explained with Examples | Replace Text in SQL Server
What is SQL? Complete Beginner Guide with Examples
What is SQL? Complete Beginner Guide with Examples
SQL UPPER() Explained with Examples | Convert Text to Uppercase in SQL
SQL UPPER() Explained with Examples | Convert Text to Uppercase in SQL
SQL COALESCE() Explained with Examples | Handle NULL Values in SQL
SQL COALESCE() Explained with Examples | Handle NULL Values in SQL
SQL CTE Explained with Examples | Common Table Expression Tutorial
SQL CTE Explained with Examples | Common Table Expression Tutorial
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
How to Learn SQL Fast | Beginner Guide 🚀
How to Learn SQL Fast | Beginner Guide 🚀
Top 20 SQL Queries for Practice | SQL Cheat Sheet for Beginners & Interviews
Top 20 SQL Queries for Practice | SQL Cheat Sheet for Beginners & Interviews
Top SQL Queries Every Fresher Should Practice
Top SQL Queries Every Fresher Should Practice
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
an image of a diagram that shows the different types of data flow lines and how to use them
an image of a diagram that shows the different types of data flow lines and how to use them
#oracledba #oracle19c #databaseshutdown #sql #dbacommands #learningjourney… | Prajay Kanade
#oracledba #oracle19c #databaseshutdown #sql #dbacommands #learningjourney… | Prajay Kanade
SQL Basics Made Easy 💻 | SELECT, WHERE & ORDER BY with Examples
SQL Basics Made Easy 💻 | SELECT, WHERE & ORDER BY with Examples

UNPIVOT For The Reverse Operation

You might want to reverse this operation, turning columns back into rows. That's where the UNPIVOT function comes in. Here's a simple example:

```sql SELECT SUB_ID, TEST_NAME, TEST_SCORE FROM (SELECT SUB_ID, TEST_NAME, TEST_SCORE FROM TEST_SCORES) UNPIVOT ( (TEST_SCORE FOR TEST_NAME IN (MATH_SCORE AS 'Math', LANG_SCORE AS 'Language')) ) ```

In this query, "Math" and "Language" are turned back into rows with their respective scores.

Beyond these examples, PIVOT's power really shines when you've got complex datasets and need to find hidden patterns or make your data more readable. With practice, you'll find it becomes a vital tool in your Oracle SQL toolkit. So, happy pivoting, and remember to explore and experiment to find what works best for you!

Related Articles

W3school Sql Left Join W3 Sql Select Is Not Null Sql Example Sql Create User W3schools Sql Update W3c W3 Sql Select Into Sql Union Example W3schools Sql Unpivot Example Delete Sql Query W3schools W3school Sql Outer Join