IT lexicon › Database › UNPIVOT (SQL)

UNPIVOT (SQL)

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

The opposite of PIVOT — turns columns into rows. Converts a wide table (a column per month: jan, feb, mar …) into a narrow one with a row per (month, value). Useful for normalizing "spreadsheet-shaped" data into a query-friendly form.

Use case: someone delivers data in wide form (each measurement as its own column) but you want it long/normalized for aggregation, filtering, and joins. SQL Server and Oracle have UNPIVOT syntax. A portable pattern in PostgreSQL: SELECT id, 'jan' AS month, jan AS value FROM t UNION ALL SELECT id, 'feb', feb FROM t ..., or more elegantly with LATERAL (VALUES (...)). PostgreSQL can also use unnest() with arrays. Rule of thumb: "long format" (narrow) is almost always better for analysis and storage than "wide format" (wide) — UNPIVOT is the tool to get there. A complement to PIVOT that goes the other way.

← Back to the lexicon