How to pivot a table in SQL with CASE WHEN and GROUP BY

GROUP BY gives you long lists: one row per month and status. A report usually wants a cross table instead, the way an Excel PivotTable shows it, with months down the side and statuses across the top. In SQL you build each of those columns as its own sum, and CASE WHEN decides which rows count toward it.

In short: every column of the cross table is a separate sum, such as SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END) AS open. GROUP BY decides the rows, the CASE sums decide the columns.

What you should know first: GROUP BY and CASE WHEN, and for the second and third exercises joining several tables.

Try it now

Customer service wants to see, for every customer, how many orders sit in each status: one row per customer, one column per status. If you get stuck, read the next section and then come back.

Task Customer service wants to see at a glance where each customer's orders stand. Show one row per customer with customer_id and four columns counting how many of that customer's orders are delivered, shipped, open and cancelled (in that order). Where a customer has no order with that status, show 0.

orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL

How a pivot works in SQL

Start with the long version. This counts orders by month and status:

SELECT substr(order_date, 1, 7) AS month, status, COUNT(*) AS orders
FROM orders
GROUP BY month, status;

That returns nine rows, two of them for February: 2026-02 delivered 2 and 2026-02 cancelled 1. For a report you want each month on a single line with the statuses side by side. So you group by month only and give every status a column of its own:

SELECT substr(order_date, 1, 7) AS month,
       SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
       SUM(CASE WHEN status = 'shipped'   THEN 1 ELSE 0 END) AS shipped,
       SUM(CASE WHEN status = 'open'      THEN 1 ELSE 0 END) AS open,
       SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders
GROUP BY month;
monthdeliveredshippedopencancelled
2026-013000
2026-022001
2026-033000
2026-042000
2026-051001
2026-060230

Read one column like this: for every order in the month, CASE WHEN checks whether the status matches. If it does, you get 1, otherwise 0, and SUM adds up the ones. That's the count. If you want an amount rather than a count, put the amount after THEN, for example quantity * unit_price.

The ELSE 0 is there for a reason. Without ELSE, CASE returns NULL for rows that don't match. SUM skips NULLs, so the total is still right as long as at least one row matches. If none does, though, the result is NULL instead of 0 and the report shows an empty cell.

How this maps to an Excel PivotTable

If you've built PivotTables in Excel, every part is still there. You just write it out yourself:

Excel PivotTableSQL
Rowscolumn in GROUP BY (here the month)
Columnsone SUM(CASE WHEN … END) line per value
Values as Sum or CountSUM with the amount, or with 1, after THEN
FiltersWHERE
Grouping itemsCASE WHEN status IN ('shipped', 'open')

The big difference is that Excel creates the columns for you from whatever values turn up in the data. In SQL you name every column. If a new status such as "returned" appears tomorrow, it won't show up in your query until you add a line for it. That cuts both ways: your report always has the same columns, even in a month with no cancellations.

One more: months as columns

Now flip it around. Categories become rows, months become columns, and instead of counting you add up revenue. This one needs three tables.

Task Purchasing wants revenue by category for the first half of 2026, laid out like a pivot table: one row per category and one column each for January to June (jan, feb, mar, apr, may, jun). Revenue is quantity times unit_price from the order items, and cancelled orders don't count. Months without revenue show 0.

orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
order_items 38 rows, 4 columns
order_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.9
products 12 rows, 5 columns
product_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Putting two values in one column

In the last exercise one column covers two statuses. IN handles that in a single condition.

Task Management wants to know how the order value of each customer segment splits by processing stage. Show one row per segment with three columns: delivered (value of delivered orders), pending (value of orders that are shipped or open) and cancelled (value of cancelled orders). An order's value is the sum of quantity times unit_price over its items. Where there's nothing, show 0.

customers 12 rows, 7 columns
customer_idnamecitycountrycustomer_sincesegmentphone
1Harbor Fremont PartnersBostonUSA2021-03-15Business617-555-0142
2Emily CarterChicagoUSA2022-07-01ConsumerNULL
3Riverside County OfficeRiversideUSA2020-11-20Government951-555-0110
4Raj PatelLeedsUK2023-01-09Consumer0113 496 0123
5Lakeview Hotel LtdManchesterUK2022-04-18Business0161 496 0456
6Olivia BrooksAustinUSA2024-02-27ConsumerNULL
7Greene & Shaw LLPLondonUK2021-09-05Business020 7946 0321
8Maple Grove High SchoolAustinUSA2023-08-14School512-555-0187
9Chloe EvansBostonUSA2025-05-30Consumer617-555-0199
10Northline Printing CoTorontoCanada2020-06-12Business416-555-0133
11Daniel KimSeattleUSA2024-10-03ConsumerNULL
12Westbrook Dental ClinicChicagoUSA2022-12-01Business312-555-0164
orders 18 rows, 5 columns
order_idcustomer_idorder_datestatusemployee_id
100112026-01-08delivered3
100242026-01-12delivered4
100332026-01-20delivered3
100472026-02-03delivered4
100522026-02-11cancelled8
100612026-02-25delivered3
1007102026-03-04delivered2
100852026-03-17delivered4
100982026-03-30delivered3
101062026-04-07delivered8
1011122026-04-22delivered4
101232026-05-06delivered3
101392026-05-19cancelled8
101472026-06-02shipped4
101512026-06-10shipped3
1016112026-06-12openNULL
101742026-06-13openNULL
1018102026-06-14openNULL
order_items 38 rows, 4 columns
order_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.9

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Common mistakes

Grouping by the column that should become columns

GROUP BY customer_id, status gives you the long list again, one row per customer and status. The exercise then says your query returns too many rows. GROUP BY only gets what makes up one row of the cross table, not the value you're spreading across the columns.

COUNT with ELSE 0

COUNT(CASE WHEN status = 'open' THEN 1 ELSE 0 END) counts every order, because COUNT counts anything that isn't NULL, and 0 isn't NULL. The exercise reports that columns and row count match but not the values. Use SUM with ELSE 0, or COUNT with no ELSE.

Leaving out GROUP BY

Without GROUP BY, SUM rolls the whole table into a single row, and the exercise says your query returns only 1 row. The condition isn't the problem here; the grouping is missing.

Filtering cancellations too early

If one column is meant to show cancelled orders, there can't be a WHERE status <> 'cancelled' in front of it, or that column stays 0 everywhere. Use WHERE only for rows that belong in none of the columns.

Pivoting in MySQL, PostgreSQL, SQL Server and SQLite

The CASE WHEN approach runs the same way in all four. Each also has its own extras:

DatabaseBuilt-in pivotShorter conditional sum
MySQLnone; the SELECT syntax has no PIVOT clauseSUM(IF(status = 'open', 1, 0))
PostgreSQLcrosstab() from the tablefunc extensionCOUNT(*) FILTER (WHERE status = 'open')
SQL Serverthe PIVOT operatorSUM(IIF(status = 'open', 1, 0)); IIF is shorthand for CASE
SQLite (these exercises)noneFILTER (WHERE …) since version 3.30.0

Here is the first exercise written with PIVOT in SQL Server:

SELECT customer_id, [delivered], [shipped], [open], [cancelled]
FROM (SELECT order_id, customer_id, status FROM orders) AS src
PIVOT (COUNT(order_id)
       FOR status IN ([delivered], [shipped], [open], [cancelled])) AS pvt;

The columns are still spelled out, this time in the list after IN. Microsoft notes that NULL values in the value column are ignored when the aggregate is calculated. In PostgreSQL, crosstab turns a query with three columns (row name, category, value) into a cross table, and you declare the names and data types of the output columns yourself in the FROM clause. The exercises on this page check for CASE, because that version runs everywhere.

Sources: Microsoft Learn (Using PIVOT and UNPIVOT, IIF), PostgreSQL documentation (tablefunc, Aggregate Expressions), MySQL Reference Manual (SELECT Statement, Flow Control Functions), sqlite.org (SELECT, Aggregate Functions, release 3.30.0).

FAQ

Can SQL create the columns automatically from the data?

Not in a plain query. The columns of a result are fixed before any data is read. If you need columns that depend on the data, you build the query text in a program or a stored procedure first. For reports with a fixed set of columns, such as twelve months, CASE WHEN is simpler.

SUM or COUNT: which is better?

Either works. SUM(CASE WHEN … THEN 1 ELSE 0 END) and COUNT(CASE WHEN … THEN 1 END) give the same count. You need SUM for amounts anyway, so sticking to SUM keeps things consistent.

How do I add a total column?

Add one more aggregate without CASE, for example COUNT(*) AS total or SUM(quantity * unit_price) AS total. It covers every row in the group, whatever the status.

Can I go the other way, from columns to rows?

Yes, that's called unpivoting. SQL Server has an UNPIVOT operator for it. In any database you can do it with UNION ALL: one query per column that returns the column name as text plus its value.

Up next: finding duplicates

Has a customer been entered twice? GROUP BY with HAVING finds duplicate records, and ROW_NUMBER keeps just the first one of each.

Practice finding duplicates

Write to us

Choose language

Select your preferred language