// window functions

Pivot & unpivot: turning rows into columns, and back again

A pivot turns a long list of transactions into a spreadsheet-style grid. Unpivot does the reverse. Neither is a keyword in Postgres, both are patterns you build by hand.

Published 12 Jul 202610 min read47 reads

A pivot turns a "long" table (one row per fact) into a "wide" one (one row per period, with a separate column for each category). It's exactly what Excel's PivotTable does. You're just building the grid by hand, using the conditional-aggregation trick from the last article.

🎯 Explain Like I'm Hired Picture a long list of transactions, one row per sale, with a category column. Pivoting turns that into a grid: one row per month, one column per category, with the totals filled in. You build it with one SUM(CASE ...) column per category you want in the grid. Example: turning "one row per order" into "one row per month, with a column for each product category's revenue" is a pivot, the shape someone wants when they ask for a dashboard-ready table instead of raw transactions.

SELECT
  DATE_TRUNC('month', order_date) AS month,
  SUM(CASE WHEN category = 'electronics' THEN amount ELSE 0 END) AS electronics,
  SUM(CASE WHEN category = 'groceries'   THEN amount ELSE 0 END) AS groceries
FROM orders
GROUP BY 1
ORDER BY 1;

Sign up to keep reading

Sign up free to unlock the worked examples, edge cases, and interview traps below.