SQL pivot
The portable way to pivot is conditional aggregation: one SUM(CASE WHEN category = 'x' THEN value ELSE 0 END) per output column, with GROUP BY on the row key. SELECT SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid, SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS refunded FROM orders turns the status rows into two columns.
Syntax
SELECT row_key, SUM(CASE WHEN col = 'A' THEN value ELSE 0 END) AS a, SUM(CASE WHEN col = 'B' THEN value ELSE 0 END) AS b FROM table GROUP BY row_key;| Part | What it is |
|---|---|
row_key | The column whose distinct values become the rows of the pivot (month, country, department) |
col | The column whose distinct values become the new columns (status, category, year) |
value | What to add up in each cell: a number such as amount, or 1 to count rows |
Examples
SELECT
SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid,
SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS refunded,
SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending
FROM orders;Result: paid 11, refunded 2, pending 1 (one row)
The same data as SELECT status, COUNT(*) ... GROUP BY status, laid out sideways.
SELECT to_char(order_date, 'YYYY-MM') AS month,
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) AS paid_amount,
SUM(CASE WHEN status = 'refunded' THEN amount ELSE 0 END) AS refunded_amount
FROM orders
GROUP BY month
ORDER BY month;Result: 2025-01 400.5 0; 2025-02 310 45; 2025-03 285 0; 2025-04 325 0; 2025-05 220 180
Add GROUP BY for a pivot with several rows. In SQLite use strftime('%Y-%m', order_date) for the month.
SELECT COUNT(*) FILTER (WHERE status = 'paid') AS paid,
COUNT(*) FILTER (WHERE status = 'refunded') AS refunded
FROM orders;Result: paid 11, refunded 2
FILTER is shorter than CASE and works in PostgreSQL and SQLite 3.30 or later; MySQL and SQL Server do not support it.
SELECT d.name AS department, COUNT(*) AS headcount,
SUM(CASE WHEN e.salary >= 90000 THEN 1 ELSE 0 END) AS over_90k
FROM employees e JOIN departments d ON d.id = e.dept_id
GROUP BY d.name
ORDER BY d.name;Result: Engineering 3 3; Finance 2 0; Sales 3 1; Support 2 0
A pivot column can be any condition, not only an equality on one column.
Try it yourself
Return one row with three columns: the number of paid orders, refunded orders and pending orders, in that order.
orders(id, customer_id, order_date, amount, status)
Free, no account needed. PostgreSQL runs in your browser and your answer is checked again on changed data.
Common mistakes
- Writing CASE WHEN status = 'paid' THEN 1 END without ELSE 0 is fine inside SUM (NULLs are skipped) but makes AVG wrong, because the ELSE rows are no longer counted; use ELSE 0 for averages or COUNT(CASE ...) for counts.
- Forgetting GROUP BY when the SELECT mixes a plain column with the SUM columns gives one arbitrary row in SQLite and MySQL and an error elsewhere.
- Expecting the pivot to grow new columns when new statuses appear: SQL needs the column list at write time, so a new status silently falls out of the report until you add a CASE for it.
- Using the PIVOT keyword in PostgreSQL, MySQL or SQLite, which do not have it; conditional aggregation is the portable form.
More practice: Pivot rows to columns
These drills check your answer on live data, free, no account needed.
- Orders per statusReturn each order status and how many orders have it.
- Label with CASEReturn each order id with a label: large when the amount is 150 or more, otherwise small.
Questions
Is there a PIVOT keyword in SQL?
Only in SQL Server and Oracle: SELECT * FROM (source) PIVOT (SUM(amount) FOR status IN ([paid], [refunded])) AS p. PostgreSQL has the crosstab function in the tablefunc extension. Everywhere else, and in interviews, use SUM(CASE WHEN ...) with GROUP BY.
How do I pivot when the column values are not known in advance?
Plain SQL cannot: the column list is fixed when the query is written. Either query the distinct values first and build the SQL in application code, or return the long form (one row per key and category) and pivot in the reporting tool or a pandas pivot_table.
How do I unpivot columns back into rows?
Use UNION ALL, one SELECT per column: SELECT month, 'paid' AS status, paid_amount AS amount FROM t UNION ALL SELECT month, 'refunded', refunded_amount FROM t. PostgreSQL also allows CROSS JOIN LATERAL (VALUES ...) and SQL Server has UNPIVOT.
Related
- CASE WHENCASE WHEN returns different values depending on conditions. Label rows, bucket numbers into ranges, pivot with SUM(CASE ...), sort custom orders, handle NULL.
- GROUP BYGROUP BY collapses rows that share a value into one row per group so you can count, sum or average them. One or several columns, the must-appear rule, HAVING.
- SUM, AVG, MIN, MAXThe core aggregates: SUM adds values, AVG averages them, MIN and MAX find the smallest and largest. NULL handling, integer division in AVG, use with GROUP BY.
- COUNTCOUNT(*) counts rows, COUNT(column) counts non-NULL values, COUNT(DISTINCT column) counts unique values. Examples with WHERE, GROUP BY and conditional counts.