SQL Server · Advanced Querying

PIVOT and UNPIVOT

Reports often need months or categories as columns. PIVOT rotates rows into columns; UNPIVOT does the opposite.

Intermediate 5 min Lesson 32 of 44Examples run on SQL Server 2022 and Azure SQL Database.
0/44 in SQL Server
On this page · 5 min · Intermediate

Learning objectives#

  • Write a PIVOT query
  • Use conditional aggregation instead
  • UNPIVOT columns into rows
  • Know the limits of static column lists

Explanation#

PIVOT needs three things: the value to aggregate (SUM(Total)), the column whose values become headings (MonthName) and the list of headings ([Jan], [Feb], [Mar]). Every other column in the source becomes a row grouping, so select only the columns you need in a derived table first.

Conditional aggregation — SUM(CASE WHEN Month = 1 THEN Total END) AS Jan — gives the same result, works in every SQL database and is easier to extend with several measures.

The column list is fixed when you write the query. For headings that change (every product category), build the list with dynamic SQL — see the Dynamic SQL lesson.

UNPIVOT turns columns like Q1, Q2, Q3, Q4 back into rows; CROSS APPLY (VALUES …) does the same and keeps NULLs.

Step-by-step screens#

Drawings of SQL Server 2022 Setup and SQL Server Management Studio (SSMS 20) with the ShopDB sample database. The red numbers match the numbered actions under each picture; names on your computer will differ.

Loading pictures…

Code example: Sales per category per month#

SQLSales per category per month Illustrative
SELECT Category, [1] AS Jan, [2] AS Feb, [3] AS Mar
FROM (
    SELECT p.Category, MONTH(o.OrderDate) AS M, oi.Quantity * oi.UnitPrice AS Amount
    FROM Orders o
    JOIN OrderItems oi ON oi.OrderId = o.OrderId
    JOIN Products p    ON p.ProductId = oi.ProductId
    WHERE o.OrderDate >= '2026-01-01' AND o.OrderDate < '2026-04-01'
) AS src
PIVOT (SUM(Amount) FOR M IN ([1], [2], [3])) AS pvt
ORDER BY Category;


-- Same result with conditional aggregation
-- SELECT p.Category,
--        SUM(CASE WHEN MONTH(o.OrderDate) = 1 THEN oi.Quantity * oi.UnitPrice END) AS Jan, ...
Expected output
Category      Jan        Feb        Mar
------------  ---------  ---------  ---------
Accessories   41,200.00  38,950.00  52,310.00
Laptops       2,10,500   1,98,000   2,44,900
Monitors      66,400.00  71,250.00  NULL

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. The derived table selects only Category, month and amount.
  2. PIVOT sums Amount for each month value 1, 2, 3.
  3. Each month becomes a column, renamed Jan–Mar.
  4. NULL means no sales that month.

Real-world use case#

The finance team gets a category-by-month grid straight from SQL Server instead of copying data into Excel pivot tables every month.

Common mistakes#

Extra columns in the source

Every extra column becomes part of the grouping and splits the rows. Select only what you need in a derived table.

Expecting dynamic headings

PIVOT needs a fixed list. Build it with STRING_AGG and sp_executesql when it changes.

Best practices#

  • Pre-select columns in a derived table
  • Prefer conditional aggregation for several measures
  • Use ISNULL to show 0 instead of NULL
  • Generate dynamic lists safely with QUOTENAME

Remember this#

PIVOT (agg FOR col IN ([a],[b])).

Only needed columns in the source.

CASE inside SUM is the portable alternative.

Practice exercise#

Your task: Show 0 instead of NULL for the Mar column in the PIVOT result.

Show solution
SQL Illustrative
SELECT Category, ISNULL([3], 0) AS Mar FROM ... PIVOT (...) AS pvt;

Mini quiz#

PIVOT and UNPIVOT quizMultiple choice Question 1 of 1

What does UNPIVOT do?

Score so far: 0/0

Want more? Practise all SQL Server MCQs · SQL Server interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.