This lesson on PIVOT and UNPIVOT in SQL is hands-on and example-driven. You will transform relational table layouts in SQL by rotating categorical row values into distinct columns using the PIVOT operator and reversing wide column structures back into normalized rows using UNPIVOT. You will apply aggregations to cross-tabulate reporting metrics and manage missing category intersections across transformed datasets.
What You'll Be Able To Do
- Transform row-level category values into distinct column headers using the PIVOT operator.
- Aggregate metric values using functions like SUM within cross-tabulation clauses.
- Reconstruct normalized row records from column-oriented datasets using the UNPIVOT operator.
- Structure derived table aliases and select column lists required by PIVOT and UNPIVOT syntax.
- Identify and interpret NULL values generated at empty category intersections during table transformations.
Detailed Concept Walkthrough
1. Relational Transposition With PIVOT
The PIVOT operator rotates row-based category values into distinct column headers to produce summarized, cross-tabulated reporting views. It reshapes a tall, narrow table into a wider table format.
- Mechanism: The PIVOT operator inspects values inside a specified column (such as
department) and rotates distinct categories (such assalesandaccounting) into new column attributes on the resulting dataset. This transforms narrow, vertical datasets into wider, horizontal presentation formats suitable for analytical inspection. - Syntax Rule: The outer
SELECTlist must explicitly request the non-pivoted identifiers alongside the newly declared pivoted column names. An alias for the pivoted subquery result (e.g.,AS pivot_table) is mandatory in SQL syntax to treat the pivoted set as a valid derived relational source. - Data Representation: When an individual entity does not possess records for a specific pivoted category, SQL populates the corresponding new column intersection with a
NULLvalue. For instance, an employee belonging solely tosaleswill automatically receive aNULLunder theaccountingcolumn.
-- Transform department row values into dedicated columns
SELECT
employee_id,
sales,
accounting
FROM employee
PIVOT (
SUM(salary)
FOR department IN (sales, accounting)
) AS pivot_table;
Key Takeaway: PIVOT reshapes categorical rows into separate columns and populates absent category intersections with NULL.
2. Aggregation Mechanics In PIVOT
Pivoting requires aggregating metric values because multiple source rows can map to a single entity-column intersection. The specified aggregate function consolidates these values during transposition.
- Aggregation Requirement: The PIVOT clause mandates an aggregate function, such as
SUM(salary), to condense intersecting metric values into the target column cells. Without an aggregate function, SQL cannot resolve multiple row records corresponding to the same grouping key. - Grouping Context: Any column present in the source table that is not specified inside the aggregate function or the
FOR ... INclause automatically forms the implicit grouping key. In theemployeetable example,employee_idbecomes the row-level anchor around which values are pivoted. - Under the Hood: The SQL execution engine computes grouping aggregations across each distinct entity and redistributes the summarized numbers into the explicit target columns declared in the
INlist. Missing intersections bypass aggregation calculations and immediately yieldNULL.
-- Aggregating salaries during column transposition
SELECT
employee_id,
sales,
accounting
FROM employee
PIVOT (
-- Mandatory aggregate function to summarize pivoted measures
SUM(salary)
FOR department IN (sales, accounting)
) AS pivot_table;
Key Takeaway: Every PIVOT operation requires an explicit aggregate function to consolidate values into new columns.
3. Normalizing Columns With UNPIVOT
The UNPIVOT operator performs the inverse of PIVOT by converting existing column headers back into normalized row values. It unpacks wide tables into tall transactional records.
- Mechanism: The UNPIVOT operator extracts column header names (e.g.,
sales,accounting) and writes them as values inside a single target descriptor column (e.g.,department), while placing the intersecting cell contents into a value column (e.g.,salary). - Structural Difference: Unlike PIVOT, UNPIVOT does not utilize an aggregate function (such as
SUM) because it is splitting existing column values into individual row items rather than condensing multiple rows. You specify the target value column directly before theFOR ... INclause. - Handling NULLs: During the unpivoting process, column intersections that contain
NULLare excluded from the output rows, naturally restoring the original normalized transactional structure of the dataset.
-- Reverse cross-tabulated columns back into transactional rows
SELECT
employee_id,
department,
salary
FROM (
SELECT employee_id, sales, accounting
FROM employee
PIVOT (SUM(salary) FOR department IN (sales, accounting)) AS p_src
) AS P
UNPIVOT (
salary
FOR department IN (sales, accounting)
) AS unpivot_table;
Key Takeaway: UNPIVOT normalizes cross-tabulated columns back into row records without requiring aggregate functions.
Topics Covered in PIVOT and UNPIVOT in SQL
- Relational Operators Overview (0:00 - 0:30) — The instructor defines PIVOT and UNPIVOT as relational operators for converting rows to columns and columns to rows.
- Sample Dataset Setup (0:30 - 1:00) — The instructor presents the employee table schema containing employee_id, department, and salary columns.
- Writing PIVOT Queries (1:00 - 2:15) — The instructor constructs a PIVOT query using SUM(salary) to generate sales and accounting columns.
- Analyzing PIVOT Output (2:15 - 3:00) — The instructor examines how pivoted columns display aggregated salaries and populate missing intersections with NULL.
- Writing UNPIVOT Queries (3:00 - 4:00) — The instructor writes an UNPIVOT query on the derived pivoted table to restore the original row-based department structure.
SQL Cheat Sheet
-
PIVOT (SUM(val_col) FOR cat_col IN (val1, val2)) AS alias— Rotates row category values into columns with aggregationSELECT employee_id, sales, accounting FROM employee PIVOT (SUM(salary) FOR department IN (sales, accounting)) AS p; -
UNPIVOT (val_col FOR cat_col IN (col1, col2)) AS alias— Rotates column headers back into normalized row valuesSELECT employee_id, department, salary FROM P UNPIVOT (salary FOR department IN (sales, accounting)) AS u; -
SUM(salary)— Aggregates metric values mapped into pivoted columnsPIVOT (SUM(salary) FOR department IN (sales, accounting)) AS p -
FOR department IN (sales, accounting)— Specifies columns or values involved in relational transpositionFOR department IN (sales, accounting)
Comparison Table
| Feature | PIVOT Operator | UNPIVOT Operator |
|---|---|---|
| Transformation Direction | Rows to columns | Columns to rows |
| Aggregation Requirement | Requires aggregate function like SUM | No aggregate function used |
| Output Layout | Wider cross-tabulated table | Narrower normalized table |
| NULL Values | Generated for missing intersections | Filtered out from output rows |
Common Pitfalls
- Mistake: Omitting the aggregate function inside the PIVOT clause. Avoid: Always wrap the value column in an aggregate function like SUM.
- Mistake: Attempting to use aggregate functions like SUM inside an UNPIVOT clause. Avoid: Specify the destination value column directly without any aggregation wrapper.
- Mistake: Forgetting to provide a table alias for the PIVOT or UNPIVOT expression. Avoid: Always append an AS alias clause immediately following the operator closing parenthesis.
- Mistake: Expecting missing row combinations to retain existing values after pivoting. Avoid: Account for NULL values appearing in pivoted columns where no corresponding source record existed.
FAQs
- Why does PIVOT require an aggregate function while UNPIVOT does not? PIVOT maps multiple rows to single cells, requiring aggregation like SUM to consolidate values. UNPIVOT unpacks distinct column cells into separate rows without combining data.
- What happens to employee records that lack values for a pivoted column? The PIVOT operation automatically fills missing category intersections with NULL values in the corresponding columns.
- Must the pivoted or unpivoted subquery always have an alias? Yes, SQL relational syntax requires derived tables produced by PIVOT and UNPIVOT operators to have an explicit table alias.