Pivoting Data

Updated · 8 min read
mediumPostgreSQL 18sqlpivotfiltercrosstabreporting

Pivoting in SQL means turning the values of one column into separate columns, so that data stored as rows is shown as a grid. It is used for reports people read across, like a spreadsheet: one row per student and one column per month, or one row per month and one column per payment method. In the database, each payment is a row; in the report, the months become columns. In this lesson, we will build pivots with PostgreSQL's FILTER clause and with the portable CASE method, and see SQL Server's PIVOT operator.

In One Minute

  • A pivot is GROUP BY the row label, plus one aggregate per column.
  • Each column's aggregate counts only its own rows: sum(amount_usd) FILTER (WHERE method = 'card').
  • The portable form is sum(CASE WHEN method = 'card' THEN amount_usd END).
  • Empty cells are NULL; wrap them in coalesce(..., 0) to show zeros.
  • The columns must be written out; a pivot with unknown columns needs dynamic SQL.

Syntax

SQL
SELECT row_label,
       aggregate(value) FILTER (WHERE column_key = 'A') AS a,
       aggregate(value) FILTER (WHERE column_key = 'B') AS b
FROM table_name
GROUP BY row_label;
PartRole
row_label in GROUP BYOne output row per value
FILTER (WHERE ...)Which rows feed this column
The aliasThe column's name

Example: Monthly Payments per Student

The following query shows, for each student, the amount paid in each month:

SQL▶ Try it
SELECT student_id,
       coalesce(sum(amount_usd) FILTER (WHERE date_trunc('month', paid_on) = '2025-08-01'), 0) AS aug,
       coalesce(sum(amount_usd) FILTER (WHERE date_trunc('month', paid_on) = '2025-10-01'), 0) AS oct,
       coalesce(sum(amount_usd) FILTER (WHERE date_trunc('month', paid_on) = '2025-11-01'), 0) AS nov,
       coalesce(sum(amount_usd) FILTER (WHERE date_trunc('month', paid_on) = '2025-12-01'), 0) AS dec,
       coalesce(sum(amount_usd) FILTER (WHERE date_trunc('month', paid_on) = '2026-01-01'), 0) AS jan,
       sum(amount_usd) AS total
FROM payments
GROUP BY student_id
ORDER BY student_id;
Output
 student_id |  aug   |  oct   |  nov   |  dec   |  jan   |  total
------------+--------+--------+--------+--------+--------+---------
        101 | 450.00 | 250.00 |      0 | 800.00 | 200.00 | 1700.00
        103 |      0 |      0 | 225.00 | 225.00 |      0 |  450.00
(2 rows)

Explanation: GROUP BY student_id makes one row per paying student. Each month column sums only the payments whose month matches its FILTER. A month with no payments gives NULL, which coalesce turns into 0. The total column has no filter, so it adds everything; it should equal the sum of the month columns, which is a quick check that no payment was missed.

Seven payment rows become two student rows with one column per month

Example: Payment Methods by Month

The row label and the column key can be any columns. Here the rows are months and the columns are payment methods:

SQL▶ Try it
SELECT to_char(date_trunc('month', paid_on), 'YYYY-MM') AS month,
       sum(amount_usd) FILTER (WHERE method = 'card')  AS card,
       sum(amount_usd) FILTER (WHERE method = 'check') AS check_total,
       sum(amount_usd) FILTER (WHERE method IS NULL)   AS unknown
FROM payments
GROUP BY 1
ORDER BY 1;
Output
  month  |  card  | check_total | unknown
---------+--------+-------------+---------
 2025-08 | 450.00 |        NULL |    NULL
 2025-10 | 250.00 |        NULL |    NULL
 2025-11 | 225.00 |        NULL |    NULL
 2025-12 | 550.00 |      475.00 |    NULL
 2026-01 |   NULL |        NULL |  200.00
(5 rows)

Explanation: December had both card and check payments; January's only payment has no method, so it lands in unknown. Note that the filter for missing methods is method IS NULL, because method = NULL would never be true. check is a reserved word in SQL, so the column is named check_total.

The Portable CASE Method

FILTER is standard SQL, but MySQL and SQL Server don't support it. The CASE form works everywhere:

SQL▶ Try it
SELECT status,
       count(CASE WHEN student_id = 101 THEN 1 END) AS srihitha,
       count(CASE WHEN student_id = 102 THEN 1 END) AS advitha,
       count(CASE WHEN student_id = 103 THEN 1 END) AS navika
FROM enrollments
GROUP BY status
ORDER BY status;
Output
  status   | srihitha | advitha | navika
-----------+----------+---------+--------
 active    |        2 |       2 |      1
 completed |        2 |       0 |      0
(2 rows)

Explanation: For each row, CASE returns 1 when the student matches, and NULL otherwise; count counts only the non-NULL values. The result counts each student's enrollments by status: Srihitha has two active and two completed. count(*) FILTER (WHERE student_id = 101) is the same in PostgreSQL.

DatabasePivot method
PostgreSQL, SQLiteFILTER (WHERE ...) or CASE
MySQLCASE (or IF)
SQL ServerCASE, or the PIVOT operator
OracleCASE, or PIVOT
sum(x) FILTER (WHERE m = 'card') and sum(CASE WHEN m = 'card' THEN x END) produce the same column

SQL Server's PIVOT

SQL Server (and Oracle) have a PIVOT operator that writes the same idea differently:

SQL
-- SQL Server only
SELECT student_id, [card], [check]
FROM (SELECT student_id, method, amount_usd FROM payments) AS src
PIVOT (SUM(amount_usd) FOR method IN ([card], [check])) AS p;

Oracle's PIVOT lists quoted values instead of brackets: PIVOT (SUM(amount_usd) FOR method IN ('card' AS card, 'check' AS check_total)). Both still need the column values listed in advance. A pivot whose columns depend on the data (every month that exists, for example) needs the column list built by a program or by dynamic SQL; PostgreSQL's tablefunc extension offers a crosstab function for this. Tabs showing each database's version are coming to this course.

FILTER, CASE and SQL Server's PIVOT operator building card and check columns per student

Common Mistakes

Forgetting GROUP BY. Without it, the whole table becomes one row.

NULL cells where 0 is expected. Wrap each column in coalesce(..., 0).

method = NULL in a filter. Use method IS NULL.

Expecting new months to appear on their own. Pivot columns are fixed; add a column for each new value.

Interview Corner

How do you pivot rows into columns in SQL?

GROUP BY the row label and write one conditional aggregate per output column, such as sum(amount) FILTER (WHERE month = 'Dec') or sum(CASE WHEN month = 'Dec' THEN amount END).

What is the FILTER clause?

A standard SQL clause on an aggregate, agg(x) FILTER (WHERE condition), that makes the aggregate use only the rows meeting the condition. PostgreSQL and SQLite support it.

Can a pivot have columns that depend on the data?

Not in plain SQL: output columns must be known when the query is written. Data-dependent columns need dynamic SQL or a reporting tool.

Practice

Challenge: For each course technology, count the enrollments by status, with columns active and completed, using FILTER. Join enrollments to courses for the technology, and sort by technology.

Show solution
SQL▶ Try it
SELECT c.technology,
       count(*) FILTER (WHERE e.status = 'active')    AS active,
       count(*) FILTER (WHERE e.status = 'completed') AS completed
FROM enrollments AS e
JOIN courses AS c USING (course_id)
GROUP BY c.technology
ORDER BY c.technology;
Output
 technology | active | completed
------------+--------+-----------
 Java       |      2 |         2
 JavaScript |      1 |         0
 SQL        |      2 |         0
(3 rows)

Java has the only completed enrollments (Srihitha's first two courses). Git doesn't appear because nobody is enrolled in Git Basics; a LEFT JOIN from courses would add it with zeros.

Quick check: Pivoting data

3 questions
1What makes each pivot column count only its own rows?
2A student paid nothing in November. What does sum(amount_usd) FILTER (WHERE month = November) give for that student?
3Which pivot method works in MySQL?

Key Takeaways

You want toWrite
A filtered columnsum(amount_usd) FILTER (WHERE method = 'card') AS card
Portable versionsum(CASE WHEN method = 'card' THEN amount_usd END) AS card
Zero instead of NULLcoalesce(sum(...) FILTER (...), 0)
Counts per columncount(*) FILTER (WHERE status = 'active')

Was this tutorial helpful?

Lesson 68 of 115