PIVOT in SQL: How to Turn Rows into Columns
How to turn rows into columns using CASE+GROUP BY and FILTER. Step-by-step examples on a real database
Say the database stores product sales by quarter. A standard GROUP BY returns this:
| product | quarter | revenue |
|---|---|---|
| Laptop | Q1 | 100 |
| Laptop | Q2 | 150 |
| Laptop | Q3 | 130 |
| Phone | Q1 | 200 |
| Phone | Q2 | 120 |
| Phone | Q3 | 180 |
| Tablet | Q1 | 80 |
| Tablet | Q2 | 95 |
| Tablet | Q3 | 110 |
But for a report, we want quarters as columns:
| product | Q1 | Q2 | Q3 |
|---|---|---|---|
| Laptop | 100 | 150 | 130 |
| Phone | 200 | 120 | 180 |
| Tablet | 80 | 95 | 110 |
This conversion from rows to columns is called PIVOT. In this article we'll explore how to do it in SQL using a delivery service database as an example.
The Problem: "Long" Format
SELECT
event_name,
platform,
COUNT(*) AS cnt
FROM events
GROUP BY event_name, platform
ORDER BY event_name, platform;| event_name | platform | cnt |
|---|---|---|
| add_to_cart | Android | 57 |
| add_to_cart | iOS | 72 |
| add_to_cart | Web | 76 |
| app_open | Android | 130 |
| app_open | iOS | 132 |
| app_open | Web | 128 |
| purchase | Android | 24 |
| purchase | iOS | 32 |
| purchase | Web | 34 |
| view_item | Android | 94 |
| view_item | iOS | 103 |
| view_item | Web | 99 |
This is the "long" format. Each combination of "event + platform" occupies a separate row. To compare iOS with Android for a single event, you have to scan through the rows manually.
What we actually want is this:
| event_name | iOS | Android | Web |
|---|---|---|---|
| app_open | 132 | 130 | 128 |
| view_item | 103 | 94 | 99 |
| add_to_cart | 72 | 57 | 76 |
| purchase | 32 | 24 | 34 |
Platforms became columns, and each event type is a single row. This is exactly the result we want.
How to Build a PIVOT: The Algorithm
Before writing the query, it helps to answer three questions:
- What becomes the rows? event_name (event type)
- What becomes the columns? platform (iOS, Android, Web)
- What is the value in each cell? COUNT(*) (number of events)
CASE + GROUP BY: The Universal Approach
This approach works in any database: MySQL, PostgreSQL, SQLite, SQL Server.
SELECT
event_name,
SUM(CASE WHEN platform = 'iOS' THEN 1 ELSE 0 END) AS iOS,
SUM(CASE WHEN platform = 'Android' THEN 1 ELSE 0 END) AS Android,
SUM(CASE WHEN platform = 'Web' THEN 1 ELSE 0 END) AS Web
FROM events
GROUP BY event_name
ORDER BY event_name;| event_name | iOS | Android | Web |
|---|---|---|---|
| add_to_cart | 72 | 57 | 76 |
| app_open | 132 | 130 | 128 |
| purchase | 32 | 24 | 34 |
| view_item | 103 | 94 | 99 |
But how does this actually work? Let's break it down step by step.
What Happens Inside
To understand the mechanics, let's remove SUM and GROUP BY from the query and see what CASE computes for each individual row:
SELECT
event_name,
platform,
CASE WHEN platform = 'iOS' THEN 1 ELSE 0 END AS "iOS",
CASE WHEN platform = 'Android' THEN 1 ELSE 0 END AS "Android",
CASE WHEN platform = 'Web' THEN 1 ELSE 0 END AS "Web"
FROM events
WHERE event_name IN ('app_open', 'purchase')
LIMIT 6;Each CASE checks the platform and assigns 1 for a match, 0 otherwise. Here's a sample of the result for clarity:
| event_name | platform | iOS | Android | Web |
|---|---|---|---|---|
| app_open | iOS | 1 | 0 | 0 |
| app_open | Android | 0 | 1 | 0 |
| app_open | iOS | 1 | 0 | 0 |
| app_open | Web | 0 | 0 | 1 |
| purchase | Android | 0 | 1 | 0 |
| purchase | iOS | 1 | 0 | 0 |
This sample shows rows from two groups: app_open and purchase. Each row gets 1 in exactly one column, and 0 in the rest. For example, a row with platform = 'iOS' gets 1 only in iOS.
Then GROUP BY groups rows by event_name, and SUM adds up the values within each group. The number of ones in the iOS column equals the number of events from iOS.
Note the ELSE 0 in CASE: without it, non-matching rows get NULL instead of 0, and the SUM result may also turn out NULL. More on this in the "NULL Trap" section below.
Why SUM and not COUNT? SUM is more convenient: just replace 1 with amount to calculate totals instead of counts. That's exactly what we'll do in the next example.
From Counts to Totals
So far we've been counting events. What if you need monetary totals instead? Just replace 1 with a real column, for example total_amount. Let's take another table from the same database, orders, and build a revenue report by order status for each month:
SELECT
DATE_FORMAT(order_date, '%Y-%m') AS month,
SUM(CASE WHEN status = 'delivered' THEN total_amount ELSE 0 END) AS delivered,
SUM(CASE WHEN status = 'canceled' THEN total_amount ELSE 0 END) AS canceled,
SUM(CASE WHEN status = 'refunded' THEN total_amount ELSE 0 END) AS refunded
FROM orders
WHERE order_date >= '2024-01-01' AND order_date < '2024-07-01'
GROUP BY month
ORDER BY month;| month | delivered | canceled | refunded |
|---|---|---|---|
| 2024-01 | 251.28 | 83.16 | 26.05 |
| 2024-02 | 513.30 | 79.68 | 80.17 |
| 2024-03 | 526.85 | 32.44 | 35.94 |
| 2024-04 | 453.75 | 62.37 | 190.28 |
| 2024-05 | 322.67 | 98.30 | 274.93 |
| 2024-06 | 267.37 | 28.22 | 55.40 |
The principle is the same: CASE WHEN filters rows by status, and SUM calculates total_amount instead of ones. Rows are months, columns are statuses, and cells contain revenue.
Things to Watch Out For
The NULL Trap
In the examples above we used ELSE 0 in CASE to guarantee a numeric result. But if you write CASE without ELSE:
SUM(CASE WHEN status = 'refunded' THEN total_amount END)...and some month has zero refunds, CASE returns NULL for every row, and SUM of all NULLs produces NULL. This is critical if you do further calculations: 100 - NULL = NULL.
There are two ways to avoid this:
Add ELSE 0 directly in CASE (as we did in the examples above):
SUM(CASE WHEN status = 'refunded' THEN total_amount ELSE 0 END)Wrap in COALESCE. Useful when the column may already contain NULL:
COALESCE(SUM(CASE WHEN status = 'refunded' THEN total_amount END), 0)You Must Know Column Values in Advance
All approaches require explicitly listing the values that become columns ('iOS', 'Android', 'Web'). If a new platform appears in the data, the query needs manual updating.
The only way around this: write a script on the application side (Python, PHP, JS) or use dynamic SQL (building the query string via PREPARE / stored procedures). Plain static SQL cannot solve this problem.
In most real-world tasks, the set of categories is known and changes rarely, so hardcoding values is perfectly normal.
Summing Up
In MySQL, CASE + GROUP BY is the only way to create a PIVOT table in plain SQL. The approach is universal, works out of the box, and is easy to read. The query gets verbose with many columns, but most reports have no more than a dozen categories.
Quick action plan:
- Determine what becomes the rows, columns, and values.
- Write a CASE WHEN for each column value.
- Wrap in SUM (or COUNT) and group by the row identifier.
- Remember ELSE 0 to avoid NULL.
Related articles
ROW_NUMBER vs RANK vs DENSE_RANK in SQL: The Difference in One Example
Three ranking functions, one query — and the difference is visible
June 15, 2026COALESCE()SQL in practice6 min read
SQL COALESCE: What It Is and How It Works — Examples | RianAcademy
The first non-NULL argument, and why NULLIF belongs nearby
June 15, 2026WITH … ASSQL in practice4 min read
CTE in SQL: What a Common Table Expression (WITH) Is — Examples
Subqueries with names, chains of steps, and recursion
June 15, 2026Article contentThe Problem: "Long" FormatHow to Build a PIVOT: The AlgorithmCASE + GROUP BY: The Universal ApproachWhat Happens InsideFrom Counts to TotalsThings to Watch Out ForThe NULL TrapYou Must Know Column Values in AdvanceSumming Up
Python Academy
