Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 08 / Topic 9 of 10

Pivoting

Reports want categories as columns — months down the side, statuses across the top. SQL's portable pivot is FILTER (Part 4's tool, graduated):

SELECT date_trunc('month', order_date)::date AS month,
       count(*) FILTER (WHERE status = 'delivered') AS delivered,
       count(*) FILTER (WHERE status = 'shipped')   AS shipped,
       count(*) FILTER (WHERE status = 'pending')   AS pending,
       count(*) FILTER (WHERE status = 'cancelled') AS cancelled
FROM orders
GROUP BY 1
ORDER BY month;
   month    | delivered | shipped | pending | cancelled 
------------+-----------+---------+---------+-----------
 2025-01-01 |         2 |       0 |       0 |         0
 2025-02-01 |         1 |       1 |       0 |         0
 2025-03-01 |         1 |       0 |       1 |         1
 2025-04-01 |         2 |       0 |       0 |         0
(4 rows)

One pass, one column per status. Its limitation is honest: the columns are written by hand, so a new status means editing the query. Postgres's tablefunc extension offers crosstab() for dynamic-ish pivots, but in practice truly dynamic columns are the reporting tool's job (Excel, BI, pandas) — SQL hands over tidy rows, or this fixed pivot.

🧪 Quick quiz — answer from memory, then check.

  1. What does each FILTER column correspond to in the pivoted result?
  2. The honest limitation of the FILTER pivot?
Show the answers
  1. One value of the pivoted category (one status), counted within the row's group (the month).
  2. Columns are hard-coded — new category values don't appear until someone edits the query.

Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.

Search the guide