Using PIVOT and UNPIVOT in SQL Server

πŸ’‘ Concept Name

PIVOT transforms rows into columns, while UNPIVOT does the reverseβ€”converting columns into rows in SQL Server.

πŸ“˜ Quick Intro

PIVOT helps reshape tabular data for better reporting, allowing values in a column to become new columns. UNPIVOT reverses that, turning columns back into rows to normalize or analyze the data further.

🧠 Analogy / Short Story

Imagine a spreadsheet with monthly sales listed vertically for each product. PIVOT flips that layoutβ€”months become columns, and products stay in rows. UNPIVOT turns it back to vertical form. It’s like rotating your spreadsheet view to see patterns differently.

πŸ”§ Technical Explanation

  • PIVOT aggregates data and turns unique values in one column into multiple columns.
  • UNPIVOT takes columns and converts them into rows under a single column name.
  • PIVOT must be applied on an aggregate function like SUM, AVG, etc.
  • UNPIVOT is useful for denormalizing wide tables into tall, analyzable formats.
  • Requires derived tables or CTEs to pre-select and format source data.

🎯 Purpose & Use Case

  • βœ… Creating dynamic reports and dashboards.
  • βœ… Transforming normalized data for visualization.
  • βœ… Simplifying comparisons across multiple columns.
  • βœ… Reformatting ETL pipeline outputs.

πŸ’» Real Code Example

-- Sample PIVOT
SELECT *
FROM (
    SELECT Product, Month, Sales
    FROM SalesData
) AS SourceTable
PIVOT (
    SUM(Sales)
    FOR Month IN ([Jan], [Feb], [Mar])
) AS PivotTable;

-- Sample UNPIVOT
SELECT Product, Month, Sales
FROM (
    SELECT Product, Jan, Feb, Mar
    FROM SalesSummary
) AS SourceTable
UNPIVOT (
    Sales FOR Month IN ([Jan], [Feb], [Mar])
) AS Unpivoted;

❓ Interview Q&A

Q1: What does the PIVOT operator do?
A: It turns row values into column headers with aggregated data.

Q2: What does UNPIVOT do?
A: It transforms columns back into rows for each value.

Q3: Can you use PIVOT without aggregation?
A: No, PIVOT requires an aggregate function like SUM or COUNT.

Q4: What is a prerequisite for PIVOT/UNPIVOT?
A: You need a derived table or subquery as the source.

Q5: Is UNPIVOT helpful for normalization?
A: Yes, it helps convert wide tables into normalized structures.

Q6: Which clause lists new column names in PIVOT?
A: The IN clause after FOR column.

Q7: Can PIVOT handle dynamic column names?
A: Not directlyβ€”you need dynamic SQL for that.

Q8: What’s a use case for PIVOT?
A: Creating monthly sales reports with months as columns.

Q9: What’s a use case for UNPIVOT?
A: Flattening product-wise sales data for analysis.

Q10: Which SQL Server version introduced PIVOT/UNPIVOT?
A: SQL Server 2005.

πŸ“ MCQs

Q1. What is the purpose of the PIVOT operator?

  • Join tables
  • Filter rows
  • Convert rows into columns
  • Update records

Q2. Which function is mandatory in PIVOT?

  • Scalar function
  • Aggregate function
  • Window function
  • String function

Q3. What does UNPIVOT convert?

  • Tables into views
  • Columns into rows
  • Views into tables
  • Rows into constraints

Q4. Can PIVOT be used with GROUP BY?

  • Yes, always
  • No, it replaces GROUP BY
  • Only with HAVING
  • Only with joins

Q5. Which clause defines column headers in PIVOT?

  • SELECT
  • GROUP BY
  • IN clause
  • WHERE

Q6. Is a subquery needed for PIVOT?

  • No
  • Yes
  • Only in MySQL
  • Only with views

Q7. What type of report is PIVOT ideal for?

  • Flat-file
  • ETL
  • Cross-tab
  • Stored procedure

Q8. Which SQL version introduced PIVOT?

  • SQL Server 2000
  • SQL Server 2005
  • SQL Server 2012
  • SQL Server 2016

Q9. Can UNPIVOT be used to normalize data?

  • No
  • Yes
  • Only in Python
  • Only with Excel

Q10. What is the output of UNPIVOT?

  • Wide and short table
  • Flat JSON
  • Tall and narrow table
  • Grouped rows

πŸ’‘ Bonus Insight

Dynamic PIVOT requires dynamic SQL because column names in the IN clause must be known at compile time. Use STUFF() and FOR XML PATH techniques to generate dynamic columns in advanced reports.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

Learn More on SQL Topics

SQL Joins Explained: INNER, LEFT, RIGHT, FULL πŸ‘‰ Explained
SQL Subqueries and Nested Queries Explained πŸ‘‰ Explained
SQL Aggregate Functions: COUNT, SUM, AVG, MIN, MAX πŸ‘‰ Explained
Understanding SQL GROUP BY and ORDER BY πŸ‘‰ Explained
Difference Between DELETE, TRUNCATE and DROP πŸ‘‰ Explained
SQL Views: Use Cases and Performance Tips πŸ‘‰ Explained
Common Table Expressions (CTE) in SQL πŸ‘‰ Explained
SQL Window Functions and OVER Clause πŸ‘‰ Explained
SQL Indexes: Clustered vs Non-Clustered πŸ‘‰ Explained
SQL Normalization and Denormalization πŸ‘‰ Explained
SQL Constraints: NOT NULL, UNIQUE, CHECK, DEFAULT πŸ‘‰ Explained
SQL Injection and How to Prevent It πŸ‘‰ Explained
Primary Key vs Foreign Key in SQL πŸ‘‰ Explained
Data Types in SQL: INT, VARCHAR, DATE and more πŸ‘‰ Explained
How to Use CASE Statement in SQL πŸ‘‰ Explained
Share:

Tags:


Feedback Modal Popup