- Advanced SQL
-
Overview
- Indexing for Performance Optimization
- Transactions and ACID Properties
- Triggers and Event Scheduling in SQL
- Window Functions and Ranking
- Pivoting Data in SQL
- JSON and XML Data Handling
- Recursive Queries in SQL
- Performance Tuning and Query Optimization
- Role-Based Access Control in Databases
- Handling Large Datasets in SQL
Pivoting Data in SQL
Add to BookmarkIntroduction
Pivoting data in SQL allows transforming row-based data into a column-based format, making it easier to analyze and generate reports. This technique is useful when dealing with categorical data that needs to be summarized across multiple dimensions.
For example, if you have sales data recorded by month, pivoting can help display each month as a separate column instead of multiple rows.
Why Use Pivoting in SQL?
Pivoting is useful for:
- Summarizing and restructuring large datasets.
- Making data easier to read and compare.
- Improving reporting and dashboard visualization.
Methods to Pivot Data in SQL
1. Using CASE with Aggregation (Standard SQL Approach)
Many databases do not have a built-in PIVOT
function. Instead, CASE
statements with aggregate functions like SUM()
, COUNT()
, or AVG()
can be used.
Example: Sales Data Pivot by Year
Suppose there is a sales
table with the following structure:
year | region | total_sales |
---|---|---|
2022 | East | 5000 |
2022 | West | 6000 |
2023 | East | 7000 |
2023 | West | 8000 |
The goal is to pivot this data so that years become columns.
Query Using CASE Statements:
SELECT region,
SUM(CASE WHEN year = 2022 THEN total_sales ELSE 0 END) AS sales_2022,
SUM(CASE WHEN year = 2023 THEN total_sales ELSE 0 END) AS sales_2023
FROM sales
GROUP BY region;
Output:
region | sales_2022 | sales_2023 |
---|---|---|
East | 5000 | 7000 |
West | 6000 | 8000 |
This method works on all SQL databases, including MySQL, PostgreSQL, SQLite, and Oracle.
2. Using the PIVOT Operator (SQL Server Only)
Some databases, like SQL Server, provide a built-in PIVOT
function to simplify pivoting.
Example: Pivoting Sales by Year in SQL Server
SELECT * FROM (
SELECT year, region, total_sales FROM sales
) AS SourceTable
PIVOT (
SUM(total_sales) FOR year IN ([2022], [2023])
) AS PivotTable;
Output:
region | 2022 | 2023 |
---|---|---|
East | 5000 | 7000 |
West | 6000 | 8000 |
The PIVOT
function simplifies queries but is only available in SQL Server.
3. Using Dynamic SQL for Dynamic Pivoting
If the column values (years, categories, etc.) are unknown beforehand, dynamic pivoting is required. This requires dynamic SQL or JSON functions, depending on the database.
Dynamic SQL Pivot Example (MySQL, PostgreSQL, SQL Server)
SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT CONCAT(
'SUM(CASE WHEN year = ', year, ' THEN total_sales ELSE 0 END) AS sales_', year
)) INTO @sql FROM sales;
SET @sql = CONCAT('SELECT region, ', @sql, ' FROM sales GROUP BY region;');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
This approach is flexible and works for any number of years dynamically.
Real-World Use Case: Monthly Sales Report
Consider a sales table with revenue categorized by month:
month | category | revenue |
---|---|---|
Jan | Electronics | 10000 |
Feb | Electronics | 12000 |
Jan | Clothing | 8000 |
Feb | Clothing | 9000 |
The goal is to pivot months into columns for better readability.
Query Using CASE Statements:
SELECT category,
SUM(CASE WHEN month = 'Jan' THEN revenue ELSE 0 END) AS Jan_Revenue,
SUM(CASE WHEN month = 'Feb' THEN revenue ELSE 0 END) AS Feb_Revenue
FROM sales
GROUP BY category;
Output:
category | Jan_Revenue | Feb_Revenue |
---|---|---|
Electronics | 10000 | 12000 |
Clothing | 8000 | 9000 |
This format makes sales data easier to compare across months.
Pivoting vs. Normal Queries
Feature | Normal Query (Rows) | Pivot Query (Columns) |
---|---|---|
Data format | Vertical (many rows) | Horizontal (fewer rows) |
Readability | Harder to compare | Easier to compare |
Reporting | Requires additional processing | Ready for reports |
Pivoting is useful when comparing multiple categories across a time period, such as sales, performance, and expenses.
Conclusion
Pivoting in SQL transforms row-based data into column-based summaries, making reports easier to read.
CASE + Aggregation
works in all SQL databases.- The
PIVOT
function is available in SQL Server for a simpler approach. - Dynamic SQL allows pivoting for unknown columns.
Choosing the right method depends on database support and reporting needs.
Prepare for Interview
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
Random Blogs
- What is YII? and How to Install it?
- Role of Digital Marketing Services to Uplift Online business of Company and Beat Its Competitors
- Google’s Core Update in May 2020: What You Need to Know
- SQL Joins Explained: A Complete Guide with Examples
- The Ultimate Guide to Starting a Career in Computer Vision
- Ideas for Content of Every niche on Reader’s Demand during COVID-19
- Career Guide: Natural Language Processing (NLP)
- Loan Default Prediction Project Using Machine Learning
- Deep Learning (DL): The Core of Modern AI
- Datasets for Exploratory Data Analysis for Beginners
- Datasets for analyze in Tableau
- Big Data: The Future of Data-Driven Decision Making
- Top 15 Recommended SEO Tools
- Understanding HTAP Databases: Bridging Transactions and Analytics
- Datasets for Speech Recognition Analysis
Datasets for Machine Learning
- Amazon Product Reviews Dataset
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset