Unpivoting in SQL: Turning Columns Into Rows
How to unpivot in SQL: UNION ALL, a lateral VALUES list, unnest, the UNPIVOT operator in SQL Server and Oracle, handling NULLs and mixed column types, unpivoting every column through JSON, and re-pivoting data into a different shape.
kvi5hnuCode Sprout team member7 min readOn this page
Pivoting (article 44) turns rows into columns for display. Unpivoting does the reverse: it turns a set of columns into rows. You need it whenever data arrives in a spreadsheet layout, with a column per month, per store or per question, and you want to query it: total it, filter it, join it, or rank it.
Wide tables are awkward in SQL. "Which store has the most stock?" needs to compare columns, "total stock across stores" needs pune + leeds + york, which breaks when a column is NULL, and adding a store means changing the table and every query. In the long form, with one row per product and store, all of these are an ordinary GROUP BY. Unpivoting is also a normalisation step (article 51): a column per store is a repeating group.
The examples use a table of stock per store, laid out like a spreadsheet:
CREATE TABLE store_stock (product_id INTEGER PRIMARY KEY, pune INTEGER, leeds INTEGER, york INTEGER);
-- (1, 4, 6, 2), (2, 1, 2, NULL), (3, 15, 10, 15), (7, 30, 25, 20)
UNION ALL
The most basic unpivot writes one SELECT per column and stacks them:
-- Stock held in each store: one column per store (a spreadsheet-style table)
CREATE TABLE store_stock (
product_id INTEGER PRIMARY KEY,
pune INTEGER,
leeds INTEGER,
york INTEGER
);
INSERT INTO store_stock VALUES
(1, 4, 6, 2),
(2, 1, 2, NULL), -- York doesn't stock the Summit 4
(3, 15, 10, 15),
(7, 30, 25, 20);
\pset null '(null)'
-- Unpivot with UNION ALL: one SELECT per column
SELECT product_id, 'pune' AS store, pune AS qty FROM store_stock
UNION ALL
SELECT product_id, 'leeds', leeds FROM store_stock
UNION ALL
SELECT product_id, 'york', york FROM store_stock
ORDER BY product_id, store;
product_id | store | qty
------------+-------+--------
1 | leeds | 6
1 | pune | 4
1 | york | 2
2 | leeds | 2
2 | pune | 1
2 | york | (null)
3 | leeds | 10
3 | pune | 15
3 | york | 15
7 | leeds | 25
7 | pune | 30
7 | york | 20
(12 rows)
Each SELECT produces one row per product for one store: a literal label, 'pune', and that column's value. UNION ALL (article 15) keeps every row. Four products times three stores gives 12 rows. The York stock for product 2 is NULL, and it's kept as a row with a NULL quantity.
This works in every database. Its drawback is that it reads the table once per column, and with many columns the query gets long. Use UNION ALL, not UNION, which would remove duplicate rows and spend time sorting.
A lateral VALUES list
The better way in PostgreSQL, and in any database with lateral joins, joins each row to a small list of (label, value) pairs built from its own columns:
-- Stock held in each store: one column per store (a spreadsheet-style table)
CREATE TABLE store_stock (
product_id INTEGER PRIMARY KEY,
pune INTEGER,
leeds INTEGER,
york INTEGER
);
INSERT INTO store_stock VALUES
(1, 4, 6, 2),
(2, 1, 2, NULL), -- York doesn't stock the Summit 4
(3, 15, 10, 15),
(7, 30, 25, 20);
-- Unpivot with a lateral VALUES list: the table is read once
SELECT s.product_id, v.store, v.qty
FROM store_stock s
CROSS JOIN LATERAL (VALUES ('pune', s.pune),
('leeds', s.leeds),
('york', s.york)) AS v(store, qty)
WHERE v.qty IS NOT NULL
ORDER BY s.product_id, v.store;
-- Once the data is long, ordinary SQL works: total stock per store
SELECT v.store, SUM(v.qty) AS total_qty
FROM store_stock s
CROSS JOIN LATERAL (VALUES ('pune', s.pune), ('leeds', s.leeds), ('york', s.york)) AS v(store, qty)
GROUP BY v.store
ORDER BY total_qty DESC;
product_id | store | qty
------------+-------+-----
1 | leeds | 6
1 | pune | 4
1 | york | 2
2 | leeds | 2
2 | pune | 1
3 | leeds | 10
3 | pune | 15
3 | york | 15
7 | leeds | 25
7 | pune | 30
7 | york | 20
(11 rows)
store | total_qty
-------+-----------
pune | 50
leeds | 43
york | 37
(3 rows)

CROSS JOIN LATERAL (VALUES ...) runs the VALUES list for each row of store_stock. Because it's lateral (article 23), the list can refer to the row's columns, s.pune, s.leeds and s.york. Each product row becomes three rows, and the table is read only once.
The WHERE v.qty IS NOT NULL filter removes the missing York stock, leaving 11 rows. Whether to keep NULLs depends on their meaning: here, NULL means "not stocked", so dropping it is right. If NULL meant "unknown" and the report must show that, keep it.
The second query shows the payoff: once the data is long, total stock per store is a plain GROUP BY store. Pune holds the most.
In SQL Server, the same technique is written CROSS APPLY (VALUES ('pune', s.pune), ...) AS v(store, qty). MySQL 8.0.14+ supports LATERAL with a derived table built from SELECT ... UNION ALL SELECT ..., as MySQL's VALUES needs the ROW() constructor. Oracle 12c+ supports CROSS APPLY and LATERAL.
Mixed types, and unnest
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Stock held in each store: one column per store (a spreadsheet-style table)
CREATE TABLE store_stock (
product_id INTEGER PRIMARY KEY,
pune INTEGER,
leeds INTEGER,
york INTEGER
);
INSERT INTO store_stock VALUES
(1, 4, 6, 2),
(2, 1, 2, NULL), -- York doesn't stock the Summit 4
(3, 15, 10, 15),
(7, 30, 25, 20);
\pset null '(null)'
-- Columns of different types must share one type in the value column
SELECT p.name, a.attribute, a.value
FROM products p
CROSS JOIN LATERAL (VALUES ('brand', p.brand),
('price', CAST(p.price AS text)),
('weight_g', CAST(p.weight_g AS text))) AS a(attribute, value)
WHERE p.product_id IN (3, 4)
ORDER BY p.name, a.attribute;
-- unnest with two arrays in parallel: labels and values
SELECT s.product_id, u.store, u.qty
FROM store_stock s,
unnest(ARRAY['pune', 'leeds', 'york'], ARRAY[s.pune, s.leeds, s.york]) AS u(store, qty)
WHERE s.product_id = 2;
name | attribute | value
------------------+-----------+--------
Basecamp lantern | brand | (null)
Basecamp lantern | price | 27.00
Basecamp lantern | weight_g | (null)
Glow head torch | brand | Lumen
Glow head torch | price | 34.50
Glow head torch | weight_g | 90
(6 rows)
product_id | store | qty
------------+-------+--------
2 | pune | 1
2 | leeds | 2
2 | york | (null)
(3 rows)
All the values in an unpivoted column must have one type. Unpivoting brand (text), price (decimal) and weight_g (integer) into one value column means casting them all to text. That's a common way to produce an "attribute, value" listing for display, but text values lose their types: they no longer sort or add up as numbers. Unpivot columns that share a meaning and a type, such as stock in each store, and keep different kinds of data in separate columns.
The lantern has no brand and no weight, so those rows show NULL.
PostgreSQL's unnest accepts several arrays and returns them side by side, one row per position. With an array of labels and an array of values, it's a compact unpivot: here for product 2, including the NULL for York.
The UNPIVOT operator
SQL Server and Oracle have an UNPIVOT clause. In SQL Server:
SELECT product_id, store, qty
FROM store_stock
UNPIVOT (qty FOR store IN (pune, leeds, york)) AS u;
Oracle's form is the same apart from the alias, and the labels are upper-case column names (PUNE, ...) unless renamed with AS:
SELECT product_id, store, qty
FROM store_stock
UNPIVOT INCLUDE NULLS (qty FOR store IN (pune AS 'pune', leeds AS 'leeds', york AS 'york'));
Two things to know:
UNPIVOTdrops rows whose value is NULL by default. Oracle'sINCLUDE NULLSkeeps them. SQL Server has no such option, so useCROSS APPLY (VALUES ...)when NULLs must be kept.- The listed columns must have the same type (SQL Server requires the same length too), so cast in a subquery first if they don't.
MySQL, PostgreSQL and SQLite have no UNPIVOT: use a lateral VALUES list, unnest, or UNION ALL.
Unpivoting every column through JSON
Every method so far lists the columns. To unpivot all of a row's columns without naming them, as in a generic audit or comparison query, convert the row to JSON and expand it:
-- Stock held in each store: one column per store (a spreadsheet-style table)
CREATE TABLE store_stock (
product_id INTEGER PRIMARY KEY,
pune INTEGER,
leeds INTEGER,
york INTEGER
);
INSERT INTO store_stock VALUES
(1, 4, 6, 2),
(2, 1, 2, NULL), -- York doesn't stock the Summit 4
(3, 15, 10, 15),
(7, 30, 25, 20);
\pset null '(null)'
-- Unpivot every column without naming them: go through JSON
SELECT s.product_id, j.key AS store, CAST(j.value AS integer) AS qty
FROM store_stock s,
jsonb_each_text(to_jsonb(s) - 'product_id') AS j
WHERE s.product_id IN (1, 2)
ORDER BY s.product_id, j.key;
product_id | store | qty
------------+-------+--------
1 | leeds | 6
1 | pune | 4
1 | york | 2
2 | leeds | 2
2 | pune | 1
2 | york | (null)
(6 rows)
to_jsonb(s) turns the whole row into a JSON object whose keys are the column names, - 'product_id' removes the key column, and jsonb_each_text returns one row per remaining key (article 43). The values arrive as text, so they're cast back to integer. If a column is added to the table, the query includes it automatically.
This is handy for generic code, such as comparing two versions of a row column by column, but the types are lost on the way and the keys come out in jsonb's internal order (shorter keys first, then alphabetically), not in table order.
Unpivot, then pivot again
Unpivoting and pivoting together reshape data: turn a table with stores as columns into one with stores as rows and products as columns.
-- Stock held in each store: one column per store (a spreadsheet-style table)
CREATE TABLE store_stock (
product_id INTEGER PRIMARY KEY,
pune INTEGER,
leeds INTEGER,
york INTEGER
);
INSERT INTO store_stock VALUES
(1, 4, 6, 2),
(2, 1, 2, NULL), -- York doesn't stock the Summit 4
(3, 15, 10, 15),
(7, 30, 25, 20);
\pset null '(null)'
-- Unpivot, then pivot back differently: stores as rows, products as columns
WITH long AS (
SELECT s.product_id, v.store, v.qty
FROM store_stock s
CROSS JOIN LATERAL (VALUES ('pune', s.pune), ('leeds', s.leeds), ('york', s.york)) AS v(store, qty)
)
SELECT store,
SUM(qty) FILTER (WHERE product_id = 1) AS ridge_2,
SUM(qty) FILTER (WHERE product_id = 2) AS summit_4,
SUM(qty) FILTER (WHERE product_id = 3) AS head_torch,
SUM(qty) FILTER (WHERE product_id = 7) AS socks
FROM long
GROUP BY store
ORDER BY store;
store | ridge_2 | summit_4 | head_torch | socks
-------+---------+----------+------------+-------
leeds | 6 | 2 | 10 | 25
pune | 4 | 1 | 15 | 30
york | 2 | (null) | 15 | 20
(3 rows)
The CTE unpivots to the long form, and the outer query pivots on product_id (article 44). Long data is the hub: from it, any wide layout is one pivot away. That's why tables should be stored long and pivoted only for display.
What's current
LATERALjoins are standard and supported by PostgreSQL, MySQL 8.0.14+, Oracle 12c+, and SQL Server asCROSS APPLY.- No mainstream database added
UNPIVOTin recent releases. PostgreSQL, MySQL and SQLite still rely on lateral joins andUNION ALL. DuckDB has anUNPIVOTstatement that can unpivotCOLUMNS(*)without listing them.
Common questions
What's the simplest way to unpivot in PostgreSQL?
CROSS JOIN LATERAL (VALUES ('label1', col1), ('label2', col2), ...) AS v(label, value).
Why are some rows missing after UNPIVOT?
UNPIVOT drops NULL values. Use INCLUDE NULLS in Oracle, or CROSS APPLY (VALUES ...) in SQL Server.
Why does my unpivot fail with a type error? All the unpivoted columns go into one column, so they need a common type. Cast them first.
Should I store data wide or long? Long, in general: one row per fact. Wide layouts are for display, and they're what pivoting produces.
Why UNION ALL and not UNION?
UNION removes duplicate rows, which would merge different products with equal values, and it costs a sort.
Summary
- Unpivoting turns a set of columns into rows, with a label column and a value column.
UNION ALLof oneSELECTper column works everywhere, but reads the table once per column.CROSS JOIN LATERAL (VALUES ...), orCROSS APPLYin SQL Server, reads the table once and is the best general method.unnestwith parallel arrays is a compact PostgreSQL alternative.UNPIVOTin SQL Server and Oracle drops NULLs by default and needs columns of one type.to_jsonb(row)withjsonb_each_textunpivots every column without listing them.- Store data long; pivot for display; unpivot then pivot to reshape.
Practice questions
Write a query that returns the total stock of each product across all stores, treating missing stock as 0, by unpivoting.
Answer
SELECT s.product_id, SUM(v.qty) AS total_qty
FROM store_stock s
CROSS JOIN LATERAL (VALUES (s.pune), (s.leeds), (s.york)) AS v(qty)
GROUP BY s.product_id
ORDER BY s.product_id;
1: 12, 2: 3, 3: 40, 7: 75. SUM ignores the NULL. Note that pune + leeds + york would give NULL for product 2.
For each product, find the store that holds the most stock.
Answer
SELECT DISTINCT ON (s.product_id) s.product_id, v.store, v.qty
FROM store_stock s
CROSS JOIN LATERAL (VALUES ('pune', s.pune), ('leeds', s.leeds), ('york', s.york)) AS v(store, qty)
WHERE v.qty IS NOT NULL
ORDER BY s.product_id, v.qty DESC, v.store;
1: leeds 6, 2: leeds 2, 3: pune 15 (tied with york, broken alphabetically), 7: pune 30. DISTINCT ON (article 10) keeps the first row per product.
How many rows does SQL Server's UNPIVOT (qty FOR store IN (pune, leeds, york)) return for the four products, and why?
Answer
- Four products times three stores is 12, but
UNPIVOTdrops the NULL value for product 2 in York.
Why must price be cast before it's unpivoted together with brand?
Answer
All the unpivoted values go into one column, which has one type. price is a decimal and brand is text, so they need a common type, here text.
Previous: Pivoting in SQL: Turning Rows Into Columns
Next: SQL Reporting Techniques: Buckets, Histograms, Shares and Running Percentages

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.