Recipe · SQL recipes

PIVOT in SQL: turning rows into columns

To turn categories into columns, group by the dimension you keep as rows and compute a conditional aggregate for each category.

Query with SUM and CASE

SQLite · fixed columns with conditional aggregation
SELECT region,
       SUM(CASE WHEN channel = 'Web'
                THEN amount_cents END) AS web_cents,
       SUM(CASE WHEN channel = 'Store'
                THEN amount_cents END) AS store_cents,
       SUM(CASE WHEN channel = 'Partner'
                THEN amount_cents END) AS partner_cents
FROM sales_pivot_demo
GROUP BY region
ORDER BY region;
Set up the example data

Amounts are in cents so this demo uses exact whole-number sums. Row 4 is a refund of 200 cents. Rows 7 and 9 have an unknown amount, which does not mean a sale of zero. The categories are set by the report, not by whichever rows happen to exist today.

SQLite · nine sample transactions
CREATE TABLE sales_pivot_demo (
  id INTEGER PRIMARY KEY,
  region TEXT NOT NULL,
  channel TEXT NOT NULL,
  amount_cents INTEGER
);
INSERT INTO sales_pivot_demo VALUES
  (1, 'North', 'Web', 1200),
  (2, 'North', 'Web', 300),
  (3, 'North', 'Store', 700),
  (4, 'North', 'Web', -200),
  (5, 'South', 'Web', 900),
  (6, 'South', 'Partner', 400),
  (7, 'South', 'Partner', NULL),
  (8, 'East', 'Store', 500),
  (9, 'West', 'Partner', NULL);

Download the full example (.sql)

The download uses an empty SQLite database with the same data and queries as this guide. Run it once on a test connection. The course's teaching editor has a limited engine, so run this script in SQLite rather than in the course lab.

Before changing the shape, look at the summary in long format. It is a handy reference for checking each cell of the grid:

SQLite · summary by region and channel
SELECT region, channel, SUM(amount_cents) AS known_amount
FROM sales_pivot_demo
GROUP BY region, channel
ORDER BY region, channel;

Summary before pivot

regionchannelknown_amount
ThisStore500
NorthStore700
NorthWeb1300
WestPartnerNULL
SouthPartner400
SouthWeb900

Verified grid: known amounts in cents

regionweb_centsstore_centspartner_cents
EastNULL500NULL
North1300700NULL
WestNULLNULLNULL
South900NULL400

For the Web column, CASE returns the amount of each Web transaction and NULL for the rest. SUM combines those contributions within each region. North holds 1200 + 300 − 200 = 1300; using MAX to “remove repeats” would return 1200 and answer a different question.

We group by region only. If you added channel to the GROUP BY, you would be back to one row per region and channel, with mostly empty columns. If you added id, you would keep one row per transaction and undo the summary. The grouping level must match the report's layout.

The known cells add up to 3800 cents, the same as SUM(amount_cents) over these nine rows. That check confirms no known amounts were lost or multiplied. It does not make the two NULL values known: the final financial total still needs them resolved.

How it works

From a long list to a report grid

At the source, each transaction has a region, a channel and an amount. The report wants one row per region and three columns: Web, Store and Partner. The channel stops repeating down the rows and moves into the header.

That transformation does not mean you should store the table that way. One physical column per channel makes adding categories and querying the set harder. Normally keep the source in long format and produce the grid when you query or export the report.

The three parts of this pivot

PartChoiceConsequence
Final rowregionOne row per region
ColumnschannelWeb, Store and Partner
MeasureSUM(amount_cents)The transactions in each cell are added up

If you already know SUM with CASE, here we apply it to a problem about the shape of the result. Changing the headers is not enough: the aggregate must keep the meaning of the data.

NULL does not always mean “no sales”

In the grid, North/Partner has no transactions; West/Partner has one, but its amount is unknown. Both cells come out NULL. South/Partner shows 400 because SUM ignores the NULL amount of the second transaction: it is a known subtotal, not a claim that both add up to exactly 400.

To tell missing records apart from pending amounts, also keep a count of transactions and a count of known values:

SQLite · telling no transactions apart from an unknown amount
WITH regions(region) AS (VALUES ('North'), ('West'))
SELECT r.region,
       COUNT(v.id) AS partner_rows,
       COUNT(v.amount_cents) AS known_amounts,
       SUM(v.amount_cents) AS known_sum
FROM regions AS r
LEFT JOIN sales_pivot_demo AS v
  ON v.region = r.region AND v.channel = 'Partner'
GROUP BY r.region
ORDER BY r.region;

Two NULL cells with different causes

regionpartner_rowsknown_amountsknown_sum
North00NULL
West10NULL

COALESCE(SUM(...), 0) turns both situations into zero. That may be fine if the report treats every gap as zero and input amounts are never unknown. With our data it would hide West's pending transaction. Choose the presentation after deciding the meaning, not to make the table look fuller.

To include a region with no transactions, start from a list of every region and LEFT JOIN the source before grouping. A region cannot appear from a transactions table that holds none of its rows. Keep filters on the right-hand table in ON when every region must be kept.

Variations and limits

The same grid with PIVOT in SQL Server

In T-SQL, PIVOT expresses the change of shape with a dedicated operator. This version assumes a table with the same data and suitable types, such as int for amount_cents. SQLite's TEXT setup is not meant to be copied as SQL Server DDL.

SQL Server · PIVOT with three explicit channels
SELECT region,
       [Web] AS web_cents,
       [Store] AS store_cents,
       [Partner] AS partner_cents
FROM (
  SELECT region, channel, amount_cents
  FROM sales_pivot_demo
) AS source
PIVOT (
  SUM(amount_cents)
  FOR channel IN ([Web], [Store], [Partner])
) AS matrix
ORDER BY region;

The source subquery selects exactly region, channel and amount. It leaves out id: columns that are neither the category nor the measure affect the pivot's grouping. Bringing the transaction id into the source can split the grid into several rows per region.

The IN list defines the columns the report returns. A new category does not create another column automatically. For more than one measure, such as amount and number of transactions, conditional aggregation usually expresses them together more clearly. Check the official PIVOT syntax (opens in a new tab) before adapting the operator.

New categories, dynamic pivots and lost detail

If a «Distribuidor» channel appears, the query will still return three columns, and that channel's amount will be left out even though the region still appears. Check the list of categories and reconcile the sums with the source; an «Others» column can make sense if the report defines one explicitly.

When the headers must follow the data, you have two options: return region/channel rows to the client and pivot them there, or build dynamic SQL. The first keeps the query's structure stable and lets a reporting tool handle the headers. In the second, the headers are SQL identifiers and cannot be passed as value parameters. Use an allow-list, the engine's identifier escaping and parameters for filters; never concatenate free text received from a user.

Do not confuse PIVOT with a transpose without aggregation. North/Web had three transactions; after the pivot only their sum remains. From that cell you can no longer tell which one was the refund or rebuild the three original rows. UNPIVOT can go back to a long format of cells, but it does not recover that detail. In SQL Server it also has specific behaviour with NULL; check whether you want to keep or drop empty cells.

Which pattern to use on each engine

Support for this approach

EngineApproach in this guideWhat to check
SQLiteSUM(CASE ...) and GROUP BYThe full examples run here
PostgreSQLConditional aggregation; FILTER as an alternativeNULL, types and how the measure is aggregated
MySQLSUM(CASE ...) and GROUP BYONLY_FULL_GROUP_BY and grouped columns
SQL ServerConditional aggregation or PIVOTSource projection and column list

For real amounts, use the exact type and scale your model requires. Whole cents work when that is the unit and you need no further fractions; DECIMAL/NUMERIC may suit other currencies, taxes or calculations. Do not convert the sum to text before aggregating.

A pivot is not guaranteed to be faster than several CASE expressions. Cut the rows down with the right filters first, check that a JOIN has not multiplied the source and review the plan with EXPLAIN. Measure with representative data and your real categories; this small example demonstrates results, not performance.

Checking another calculation

SQLite · grid of counts per channel
SELECT region,
       SUM(CASE WHEN channel = 'Web' THEN 1 ELSE 0 END) AS web_rows,
       SUM(CASE WHEN channel = 'Store' THEN 1 ELSE 0 END) AS store_rows,
       SUM(CASE WHEN channel = 'Partner' THEN 1 ELSE 0 END) AS partner_rows
FROM sales_pivot_demo
GROUP BY region
ORDER BY region;

Verified counts, including NULL amounts

regionweb_rowsstore_rowspartner_rows
East010
North310
West001
South102

South has two Partner transactions. CASE contributes one per transaction, whatever the amount. Counting amount_cents would drop the unknown value and give a different figure.