softwaretips4u Tips that Transform
← Back to Homepage ← Back to Articles

SQL PIVOT and UNPIVOT Operations

πŸ”Ή What Are PIVOT and UNPIVOT?

PIVOT converts rows into columns, often to create cross-tab reports, while UNPIVOT converts columns back into rows for data normalization. They are invaluable in reporting, dashboards, and analytics workflows.

βš™οΈ Why They Matter

🧠 Example 1 – Native PIVOT (SQL Server / Oracle)

SELECT *
FROM (
  SELECT Product, Quarter, Amount
  FROM Sales
) AS SourceTable
PIVOT (
  SUM(Amount)
  FOR Quarter IN ([Q1], [Q2])
) AS PivotTable;
πŸ“˜ Rows (Q1, Q2) become columns, showing totals per product per quarter.

🧠 Example 2 – Manual PIVOT in PostgreSQL/MySQL

SELECT
  Product,
  SUM(CASE WHEN Quarter = 'Q1' THEN Amount ELSE 0 END) AS Q1,
  SUM(CASE WHEN Quarter = 'Q2' THEN Amount ELSE 0 END) AS Q2
FROM Sales
GROUP BY Product;
πŸ’‘ The CASE + GROUP BY pattern works universally when native PIVOT is unavailable.

🧠 Example 3 – UNPIVOT (Reverse Transformation)

SELECT Product, Quarter, Amount
FROM SalesPivot
UNPIVOT (
  Amount FOR Quarter IN ([Q1], [Q2])
) AS UnpivotTable;
πŸ“˜ Converts columns back into row values for easier analysis or loading into fact tables.

βš™οΈ Monthly Salary Pivot

SELECT *
FROM (
  SELECT emp_id, month, salary
  FROM salaries
) AS s
PIVOT (
  SUM(salary) FOR month IN ([Jan], [Feb], [Mar], [Apr])
) AS SalaryPivot;
πŸ“˜ Produces a compact salary gridβ€”one row per employee, months as columns.

βš–οΈ Comparison Table

Operation Transforms Common Use Cases Supported In
PIVOT Rows β†’ Columns Dashboards, KPI scorecards, cross-tab summaries SQL Server, Oracle (native)
UNPIVOT Columns β†’ Rows Data warehousing, ETL, normalization SQL Server, Oracle (native)
Manual PIVOT Rows β†’ Columns Systems without PIVOT PostgreSQL, MySQL via CASE logic

πŸ’‘ Interview Soundbite

β€œUse PIVOT to rotate rows into columns for reporting, and UNPIVOT to normalize wide tables. When native syntax is missing, simulate it with CASE expressions.”
← Back to Articles | 🏠 Back to Homepage