🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

PIVOT, UNPIVOT, and Conditional Aggregation

Advanced SQLTransformationđŸŸĸ Free Lesson
Advanced SQL

PIVOT, UNPIVOT, and Conditional Aggregation

Reports often arrive as tidy rows and leave as wide grids. Reshaping is a skill you will use in every quarterly review, export, and spreadsheet handoff.

  • Native PIVOT — syntax in SQL Server and Oracle, and what the compiler expands it into
  • CASE aggregation — the portable form that works on every engine
  • UNPIVOT tricks — turning columns back into rows, including CROSS APPLY VALUES
  • Dynamic pivots — generating column lists at runtime without SQL injection If you understand conditional aggregation, you already understand pivot.

Prerequisites

  • !Comfort with GROUP BY and aggregate functions
  • !Exposure to CASE expressions
  • !Basic awareness of dynamic SQL concepts (helpful for the dynamic pivot section)

What You'll Learn

  • 1Translate a row-oriented table into a pivoted report and back
  • 2Write native PIVOT/UNPIVOT where supported and CASE aggregation everywhere else
  • 3Build a dynamic pivot safely with QUOTENAME and bound parameters
  • 4Decide when pivoting belongs in SQL versus in the presentation layer

The Shape Problem

Normalized tables store facts as rows: one row per product per quarter. Stakeholders want one row per product with quarter columns. That transformation is a pivot — rows to columns. The inverse, unpivot, turns wide sensor-style tables back into tidy rows for storage or further processing.

Databases differ sharply in how they help. SQL Server provides PIVOT and UNPIVOT operators. Oracle provides PIVOT and UNPIVOT with slightly different syntax and richer options. PostgreSQL, MySQL, and SQLite have no native pivot operator; you use conditional aggregation, or in PostgreSQL the crosstab function from the tablefunc extension. Understanding the manual form matters even if your engine has the sugar, because native PIVOT compiles into something close to it and you will read that shape in plans and legacy code.

-- Source rows: one row per product per quarter
CREATE TABLE product_quarter_sales (
    product_name TEXT NOT NULL,
    fiscal_quarter TEXT NOT NULL,   -- 'Q1' .. 'Q4'
    revenue NUMERIC(12, 2) NOT NULL
);

-- Portable pivot with CASE: works on PostgreSQL, MySQL, SQL Server, SQLite
SELECT
    product_name,
    SUM(CASE WHEN fiscal_quarter = 'Q1' THEN revenue END) AS q1_revenue,
    SUM(CASE WHEN fiscal_quarter = 'Q2' THEN revenue END) AS q2_revenue,
    SUM(CASE WHEN fiscal_quarter = 'Q3' THEN revenue END) AS q3_revenue,
    SUM(CASE WHEN fiscal_quarter = 'Q4' THEN revenue END) AS q4_revenue,
    SUM(revenue) AS total_revenue
FROM product_quarter_sales
GROUP BY product_name
ORDER BY total_revenue DESC;

Notice that the CASE yields NULL for non-matching rows and the SUM skips those NULLs — that is the entire mechanism of a pivot: filter values per output column inside an aggregate. Keep total_revenue as a cross-check: the sum of the four quarter columns must equal it for every row.

Native PIVOT Syntax

SQL Server's PIVOT operator takes three arguments: the aggregation, the column to spread, and the values that become column headers.

-- SQL Server: native PIVOT over the same source data
SELECT
    product_name,
    [Q1] AS q1_revenue,
    [Q2] AS q2_revenue,
    [Q3] AS q3_revenue,
    [Q4] AS q4_revenue
FROM product_quarter_sales
PIVOT (
    SUM(revenue)
    FOR fiscal_quarter IN ([Q1], [Q2], [Q3], [Q4])
) AS p
ORDER BY product_name;

-- Oracle: same idea, slightly different grammar
-- SELECT product_name, q1, q2, q3, q4
-- FROM (
--     SELECT product_name, fiscal_quarter, revenue
--     FROM product_quarter_sales
-- )
-- PIVOT (
--     SUM(revenue) AS revenue
--     FOR fiscal_quarter IN ('Q1' AS q1, 'Q2' AS q2, 'Q3' AS q3, 'Q4' AS q4)
-- )
-- ORDER BY product_name;

Native PIVOT hides an implicit grouping: every column not named in the aggregation or the FOR list becomes a grouping key. If your source has extra columns, they silently change the grain of the result — a classic source of surprising rows. The operators also require an explicit value list; you cannot spread "whatever values exist" without dynamic SQL.

ApproachEnginesColumn listReadability
CASE + aggregateAllWritten by handVery portable; verbose for many columns
Native PIVOTSQL Server, OracleWritten in the statementCompact; implicit grouping surprises newcomers
crosstab (tablefunc)PostgreSQLProvided via function signatureConcise once the extension is installed
Dynamic pivotAny (with dynamic SQL)Built at runtimeRequired when categories are data-driven

UNPIVOT and Its Portable Cousins

Unpivot reverses the transformation: quarter columns become rows. SQL Server's UNPIVOT operator, and its CROSS APPLY VALUES alternative, both appear in real codebases; Oracle's UNPIVOT supports additional clause options such as EXCLUDING NULLS.

-- SQL Server: UNPIVOT four quarter columns back into rows
SELECT
    product_name,
    fiscal_quarter,
    revenue
FROM quarterly_wide
UNPIVOT (
    revenue FOR fiscal_quarter IN ([Q1], [Q2], [Q3], [Q4])
) AS u;

-- SQL Server: CROSS APPLY VALUES — more flexible, often preferred
SELECT
    w.product_name,
    v.fiscal_quarter,
    v.revenue
FROM quarterly_wide w
CROSS APPLY (VALUES
    ('Q1', w.q1),
    ('Q2', w.q2),
    ('Q3', w.q3),
    ('Q4', w.q4)
) AS v (fiscal_quarter, revenue)
WHERE v.revenue IS NOT NULL;

-- Portable unpivot with UNION ALL (works everywhere)
SELECT product_name, 'Q1' AS fiscal_quarter, q1 AS revenue FROM quarterly_wide
UNION ALL
SELECT product_name, 'Q2', q2 FROM quarterly_wide
UNION ALL
SELECT product_name, 'Q3', q3 FROM quarterly_wide
UNION ALL
SELECT product_name, 'Q4', q4 FROM quarterly_wide;

The CROSS APPLY VALUES form is worth learning even on engines that do not require it: the value list is data you can extend with derived columns, and filters like the WHERE ... IS NOT NULL above give you explicit control over dropping empty combinations — something native UNPIVOT does only with an EXCLUDING NULLS clause in supported engines.

When Categories Are Not Known at Write Time

Quarter labels and product lines change. When the pivot column values come from data — regions, statuses, sensor ids — the column list must be built at runtime. The safe recipe in SQL Server is QUOTENAME plus a system procedure; in PostgreSQL, dynamic SQL via EXECUTE in PL/pgSQL.

-- SQL Server: dynamic pivot with injection-safe quoting
DECLARE @cols NVARCHAR(MAX), @sql NVARCHAR(MAX);

SELECT @cols = STRING_AGG(QUOTENAME(fiscal_quarter), ',')
               WITHIN GROUP (ORDER BY fiscal_quarter)
FROM (SELECT DISTINCT fiscal_quarter FROM product_quarter_sales) AS d;

SET @sql = N'
SELECT product_name, ' + @cols + N'
FROM product_quarter_sales
PIVOT (
    SUM(revenue) FOR fiscal_quarter IN (' + @cols + N')
) AS p
ORDER BY product_name;';

EXEC sys.sp_executesql @sql;

Two safety rules govern dynamic SQL. First, never concatenate raw user input into the statement — derive column names from the data, then wrap each with QUOTENAME (SQL Server) or quote_ident (PostgreSQL) so a malicious value cannot break out of the identifier position. Second, bound parameters still apply for values that are not identifiers. If a stakeholder can type a filter value into a dashboard, it goes in as a parameter, never as string concatenation.

PostgreSQL users who prefer to avoid dynamic SQL can install tablefunc and use crosstab, whose first query returns row keys and category values and whose second parameter supplies the fixed category order. It handles the common fixed-category case cleanly; for open-ended categories, dynamic SQL remains the tool.

Testing a Pivot Before Anyone Sees It

A pivoted report is a reshaping of numbers people already trust, which makes silent drift especially embarrassing. Three checks catch almost every pivot bug before publication.

First, reconcile totals. The sum of all pivoted value columns must equal the sum of the source measure over the same filter set. If it does not, rows were dropped by an inner join, double-counted by an implicit grouping change, or lost to NULL handling. Second, compare row counts. The number of distinct grouping keys in the result must match the number of distinct keys in the source; a mismatch usually means an accidental inner join filtered out keys that had no values in some category. Third, spot-check one entity by hand: pick a single product, list its source rows, and confirm each pivoted cell against the arithmetic.

-- Reconciliation query: pivot totals versus source totals
WITH pivoted AS (
    SELECT
        product_name,
        SUM(CASE WHEN fiscal_quarter = 'Q1' THEN revenue END) AS q1,
        SUM(CASE WHEN fiscal_quarter = 'Q2' THEN revenue END) AS q2,
        SUM(CASE WHEN fiscal_quarter = 'Q3' THEN revenue END) AS q3,
        SUM(CASE WHEN fiscal_quarter = 'Q4' THEN revenue END) AS q4
    FROM product_quarter_sales
    GROUP BY product_name
)
SELECT
    (SELECT COALESCE(SUM(q1 + q2 + q3 + q4), 0) FROM pivoted) AS pivot_grand_total,
    (SELECT COALESCE(SUM(revenue), 0) FROM product_quarter_sales) AS source_grand_total;
-- The two totals must be equal; any difference is a bug in grain or filtering.

Automate these checks where the pivot feeds a dashboard: run them in the pipeline that refreshes the mart, and abort the refresh on mismatch. The queries cost milliseconds against tables that are already in memory, and they convert a class of stakeholder-facing errors into build failures the owning team sees first. Treat the reconciliation query as part of the deliverable, the same way tests travel with application code.

Where Should the Reshape Happen?

Pivoting in SQL is right when the database is the last step before delivery: a reporting view, an export for finance, or an API endpoint that must return wide JSON. Pivoting in SQL is wrong when categories explode combinatorially — thousands of distinct statuses would create thousands of columns, which no engine handles gracefully. In those cases keep the data tidy and reshape in the application or BI layer, which can pivot interactively without DDL changes.

A practical middle ground: maintain a tidy fact table, expose a pivoted view for known report shapes, and let exploratory work happen on the tidy form. Views are cheap to rewrite when the category set changes, and downstream consumers of a stable wide shape keep working.

Common Mistakes

Forgetting that native PIVOT groups by every unmentioned column

Fix: Select only the grouping keys and the pivot input in the subquery feeding PIVOT

Building dynamic pivot column lists by concatenating raw strings

Fix: Use QUOTENAME or quote_ident for every identifier and derive categories from data

Losing rows where every pivoted value is NULL

Fix: Decide deliberately: keep the row with COALESCE for display, or filter it in an outer query

Pivoting thousands of distinct categories into columns

Fix: Keep the data tidy and pivot in the presentation layer instead

Best Practices

  • Prefer CASE-based aggregation when you need cross-engine portability
  • Reconcile pivoted totals against SUM over the source before publishing
  • Use CROSS APPLY VALUES for readable unpivots with explicit NULL filtering
  • Cache dynamic pivot category lists when they change rarely, to avoid runtime DISTINCT scans
  • Document the grain of the feeding subquery next to every pivot

Interview Questions

Q1: How do you pivot without a PIVOT operator?

With conditional aggregation: SUM(CASE WHEN category = 'X' THEN value END) per output column, grouped by the non-pivoted keys. The CASE filters values into the right column and the aggregate collapses the rows.

Q2: Why can a dynamic pivot become a security risk?

If category values from data are concatenated into the statement unescaped, a crafted value can inject SQL in the identifier position. Wrap every dynamic identifier with QUOTENAME or quote_ident and never interpolate raw user text.

Q3: When would you avoid pivoting in the database?

When the number of resulting columns is unbounded or changes frequently, wide tables become brittle. Keep the fact table tidy and let the BI or application layer reshape interactively.

Key Takeaways

  • Pivot is rows-to-columns; unpivot is the reverse; both are reshapes, not new information
  • CASE plus aggregate is the portable pivot every engineer should master
  • Native PIVOT hides grouping behavior that frequently surprises newcomers
  • Dynamic pivots require injection-safe identifier quoting every time
  • Choose the reshape location — SQL view versus presentation layer — based on category cardinality
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement