SQL reference

Pivot in SQL: turn rows into columns

In Excel, you'd reach for
fxA pivot table with a field in Columns, not just Rows

GROUP BY gives you a pivot with fields in Rows only: one row per month and region. Often you want the Excel layout instead: months down the side, regions across the top. That's a pivot: turning values into columns.

The method that works in every database: group by the row field, and make one column per value with SUM(CASE WHEN …).

SQL GROUP BY explained as an Excel pivot table: orders grouped by region and summed
GROUP BY is a pivot table: rows land in buckets, then each bucket is totalled. Download · Save to Pinterest

Syntax

SELECT row_field,
  SUM(CASE WHEN col_field = 'A' THEN value END) AS a,
  SUM(CASE WHEN col_field = 'B' THEN value END) AS b
FROM table
GROUP BY row_field;
Try itEdit the query, then Run
monthnorth_americaeuropeasia_pacificlatin_americatotal
2026-01746510272313
2026-0290497476289
2026-0354738577289
2026-04101497880308
2026-055910199107366
2026-0674797748278

6 rows

Some databases have a dedicated PIVOT keyword. SQL Server:

SELECT * FROM (SELECT region, quantity FROM orders) src
PIVOT (SUM(quantity) FOR region IN ([Europe], [Asia Pacific])) p;

Snowflake, BigQuery and Oracle have similar PIVOT syntax; Postgres and MySQL don't. The SUM(CASE WHEN) version runs everywhere and is easier to read, which is why analysts tend to stick with it. The catch with both: you list the columns yourself. SQL won't invent a column per value the way an Excel pivot does.

Your turn

Tickets per agent with priorities as columns: urgent, normal, low (counts).

This page on one card

Pivot in SQL: turn rows into columns: the Excel way (A pivot table with a field in Columns) and the SQL query, side by side
Pivot in SQL: turn rows into columns, on one card: the Excel way and the SQL. Download · Save to Pinterest
The practice data (7 tables)

See every column and sample rows