Reading history

Pivot Rows to Columns in SQL

5 min read 0 views

Pivot rows into columns in any SQL database with conditional aggregation using SUM and CASE, and unpivot wide tables back into rows with UNION ALL.

Databases store data in long, narrow tables: one row per order. Managers prefer wide reports: one row per customer and one column per month or status. Turning row values into columns is called pivoting, and turning columns back into rows is unpivoting. Every SQL database can pivot with a simple trick called conditional aggregation.

In this lesson you will learn

  • What pivoting means
  • Conditional aggregation with SUM(CASE …) and COUNT(CASE …)
  • Pivoting counts and amounts by status and month
  • Unpivoting with UNION ALL
  • The limits of pivoting in SQL

You should know CASE and GROUP BY.

The Idea

Long: one row per ordercustomerstatusKarimdeliveredKarimcancelledKarimdeliveredRinadeliveredRinapendingJoyadeliveredJoyadeliveredTuhinpendingGROUP BYSUM(CASE…)Wide: one row per customercustomerdeliveredpendingcancelledJoya200Karim201Rina110Tuhin010

Group by the row label (customer), and for each new column add up only the rows that belong to it. CASE picks those rows, and the aggregate adds them.

Pivoting With CASE

-- Orders per customer, one column per status (pivot)
SELECT customer,
       SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
       SUM(CASE WHEN status = 'pending'   THEN 1 ELSE 0 END) AS pending,
       SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled,
       COUNT(*) AS total
FROM orders
GROUP BY customer
ORDER BY customer;

-- Delivered revenue by customer and month
SELECT customer,
       SUM(CASE WHEN strftime('%m', order_date) = '01' THEN amount ELSE 0 END) AS jan,
       SUM(CASE WHEN strftime('%m', order_date) = '02' THEN amount ELSE 0 END) AS feb,
       SUM(CASE WHEN strftime('%m', order_date) = '03' THEN amount ELSE 0 END) AS mar
FROM orders
WHERE status = 'delivered'
GROUP BY customer
ORDER BY customer;

Output

+----------+-----------+---------+-----------+-------+
| customer | delivered | pending | cancelled | total |
+----------+-----------+---------+-----------+-------+
| Joya     | 2         | 0       | 0         | 2     |
| Karim    | 2         | 0       | 1         | 3     |
| Rina     | 1         | 1       | 0         | 2     |
| Tuhin    | 0         | 1       | 0         | 1     |
+----------+-----------+---------+-----------+-------+
(4 rows)

+----------+------+------+------+
| customer | jan  | feb  | mar  |
+----------+------+------+------+
| Joya     | 0    | 2300 | 300  |
| Karim    | 1200 | 0    | 1500 |
| Rina     | 450  | 0    | 0    |
+----------+------+------+------+
(3 rows)
  • SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) counts delivered orders: each matching row adds 1 and the rest add 0.
  • The total column is a check: delivered + pending + cancelled should equal it. Karim has 2 + 0 + 1 = 3.
  • In the second report, strftime('%m', order_date) extracts the month and THEN amount adds money instead of counting. Joya spent 2300 in February and 300 in March.

Using ELSE 0 shows 0 for empty cells. Without ELSE, the CASE gives NULL and an empty cell would show NULL, which some reports prefer to tell “no data” from “zero”.

Unpivoting

Sometimes the data arrives wide, for example one column per exam, and you need it long so you can group and filter it.

-- A wide table: one column per exam
CREATE TABLE results (student TEXT, mid INTEGER, final INTEGER, lab INTEGER);
INSERT INTO results VALUES ('Nusrat',78,85,90),('Arif',65,72,80);

-- Unpivot: turn the columns back into rows
SELECT student, 'mid' AS exam, mid AS marks FROM results
UNION ALL
SELECT student, 'final', final FROM results
UNION ALL
SELECT student, 'lab', lab FROM results
ORDER BY student, exam;

Output

+---------+-------+-------+
| student | exam  | marks |
+---------+-------+-------+
| Arif    | final | 72    |
| Arif    | lab   | 80    |
| Arif    | mid   | 65    |
| Nusrat  | final | 85    |
| Nusrat  | lab   | 90    |
| Nusrat  | mid   | 78    |
+---------+-------+-------+
(6 rows)

Each SELECT takes one column and labels it; UNION ALL stacks them. Now AVG(marks) … GROUP BY exam is easy.

Limits and Other Tools

  • You must list every column in the query. If a new status appears next month, you add a line. SQL cannot create columns from data automatically without dynamic SQL.
  • SQL Server and Oracle have a PIVOT keyword, but conditional aggregation works in every database.
  • For reports with many changing columns, it is often easier to pivot in Excel, a BI tool or Python.

Common Mistakes

  1. Forgetting GROUP BY. Without it, the whole table collapses to one row.
  2. Using COUNT(CASE … ELSE 0 END). COUNT counts the 0s too; use SUM, or COUNT without ELSE.
  3. Mixing up text cases. 'Delivered' and 'delivered' are different values.
  4. Using UNION instead of UNION ALL when unpivoting, which removes rows that happen to be identical.

Practice Exercises

Exercise 1. Count students per city, with one column each for CSE, EEE and BBA.

Show answer
SELECT city,
       SUM(CASE WHEN dept = 'CSE' THEN 1 ELSE 0 END) AS cse,
       SUM(CASE WHEN dept = 'EEE' THEN 1 ELSE 0 END) AS eee,
       SUM(CASE WHEN dept = 'BBA' THEN 1 ELSE 0 END) AS bba
FROM students
GROUP BY city
ORDER BY city;

Dhaka has 2 CSE and 1 EEE students; Khulna and Rajshahi have 1 BBA each.

Exercise 2. Using the unpivoted query as a CTE, find the average mark for each exam.

Show answer
WITH long AS (
  SELECT student, 'mid' AS exam, mid AS marks FROM results
  UNION ALL SELECT student, 'final', final FROM results
  UNION ALL SELECT student, 'lab', lab FROM results
)
SELECT exam, AVG(marks) AS avg_marks FROM long GROUP BY exam;

final 78.5, lab 85.0, mid 71.5.

Frequently Asked Questions

Can SQLite or MySQL pivot automatically?

No. Neither has a PIVOT keyword, so you write conditional aggregation or build the query text in a program. PostgreSQL offers a crosstab function through an extension.

Some databases support FILTER. What is it?

COUNT(*) FILTER (WHERE status = 'pending') is a cleaner way to write conditional aggregation, supported by PostgreSQL and SQLite. It does the same job as SUM(CASE …).

Summary

  • Pivoting turns row values into columns; unpivoting does the reverse.
  • Conditional aggregation: GROUP BY the row label and SUM(CASE WHEN … THEN value ELSE 0 END) per column.
  • Unpivot with one SELECT per column joined by UNION ALL.
  • Columns must be listed by hand; use other tools for dynamic pivots.

Next: SQL LIKE and Pattern Matching.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *