IT lexicon › Database › PIVOT (SQL)

PIVOT (SQL)

Database På svenska → Updated: 2026-05-28

An operation that turns rows into columns — e.g. turning a long table of (month, amount) into a wide one with a column per month. Built-in PIVOT syntax in SQL Server and Oracle; in PostgreSQL it's done with CASE WHEN aggregation or crosstab().

Use case: report formats where you want "year down, month across" instead of one row per (year, month). The manual pattern (portable): SUM(CASE WHEN month = 1 THEN amount END) AS jan, SUM(CASE WHEN month = 2 ...) AS feb, ... grouped per year. Limitation: the columns must be known in advance (SQL is statically typed) → "dynamic pivot" requires building the SQL string in code. PostgreSQL has crosstab() in the tablefunc extension. Pivoting is often done instead in the presentation layer (BI tools, Python/pandas) where it's dynamic. The opposite is UNPIVOT (columns → rows).

← Back to the lexicon