Pivoting in SQL: Turning Rows Into Columns
How to pivot in SQL: conditional aggregation with FILTER and CASE, zeros and totals, pivoting by position, PostgreSQL's crosstab, the PIVOT operator in SQL Server and Oracle, dynamic pivots when the columns aren't known in advance, and JSON as a flexible alternative.
kvi5hnuCode Sprout team member9 min readOn this page
Data is stored long: one row per fact, such as one row per category and status. Reports are often wanted wide: one row per category, with a column for each status. Turning the values of one column into column headings is called pivoting, and it's what spreadsheets do with pivot tables.
SQL has no single pivot syntax that works everywhere, but one technique does: conditional aggregation, introduced in article 21. This article builds on it: totals, pivoting by position, the crosstab function and the PIVOT operator, and the hard case, where the columns aren't known until the query runs. Article 45 covers the reverse, unpivoting.
The examples use the sales view from article 20, with one row per order line: its order, date, status, category, brand, quantity and amount.
Conditional aggregation
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);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- The data, long form: one row per category and status
SELECT category, status, SUM(amount) AS amount
FROM sales
GROUP BY category, status
ORDER BY category, status;
-- Pivoted: one row per category, one column per status
SELECT category,
SUM(amount) FILTER (WHERE status = 'pending') AS pending,
SUM(amount) FILTER (WHERE status = 'shipped') AS shipped,
SUM(amount) FILTER (WHERE status = 'delivered') AS delivered,
SUM(amount) FILTER (WHERE status = 'cancelled') AS cancelled
FROM sales
GROUP BY category
ORDER BY category;
category | status | amount
----------+-----------+--------
clothing | delivered | 30.00
clothing | shipped | 64.00
lighting | delivered | 34.50
lighting | shipped | 69.00
packs | cancelled | 54.00
packs | delivered | 89.95
tents | pending | 489.00
tents | shipped | 249.99
(8 rows)
category | pending | shipped | delivered | cancelled
----------+---------+---------+-----------+-----------
clothing | | 64.00 | 30.00 |
lighting | | 69.00 | 34.50 |
packs | | | 89.95 | 54.00
tents | 489.00 | 249.99 | |
(4 rows)
The first query shows the data long: 8 rows, one per category and status. The second pivots it. The technique has three parts:
GROUP BYthe row label, herecategory, so there's one output row per category.- One aggregate per output column, each restricted to one value of the pivoted column:
SUM(amount) FILTER (WHERE status = 'shipped'). - List the columns explicitly, with an alias for each.

The cells with no matching rows are NULL: no clothing was cancelled. Any aggregate works in the cells: COUNT(*) for counts, MAX for a single value, AVG, or string_agg for a list.
FILTER is standard SQL and works in PostgreSQL and SQLite 3.30+. Everywhere else, put the condition in a CASE inside the aggregate. This is the most portable form of all:
SUM(CASE WHEN status = 'shipped' THEN amount END) AS shipped
CASE without ELSE gives NULL for the other rows, and aggregates ignore NULLs. In MySQL, a comparison is a number, 1 or 0, so SUM(status = 'shipped') counts matching rows.
Zeros, totals and periods as columns
Reports usually want 0 rather than an empty cell, a total for each row, and a total row at the bottom:
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);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- Zeros instead of NULLs, a row total, and a grand-total row
SELECT COALESCE(category, 'TOTAL') AS category,
COALESCE(SUM(amount) FILTER (WHERE placed_on >= DATE '2026-03-02' AND placed_on < DATE '2026-03-09'), 0) AS wk_2_mar,
COALESCE(SUM(amount) FILTER (WHERE placed_on >= DATE '2026-03-09' AND placed_on < DATE '2026-03-16'), 0) AS wk_9_mar,
COALESCE(SUM(amount) FILTER (WHERE placed_on >= DATE '2026-03-16' AND placed_on < DATE '2026-03-23'), 0) AS wk_16_mar,
SUM(amount) AS total
FROM sales
WHERE status <> 'cancelled'
GROUP BY ROLLUP (category)
ORDER BY GROUPING(category), category;
category | wk_2_mar | wk_9_mar | wk_16_mar | total
----------+----------+----------+-----------+---------
clothing | 48.00 | 30.00 | 16.00 | 94.00
lighting | 69.00 | 34.50 | 0 | 103.50
packs | 0 | 89.95 | 0 | 89.95
tents | 249.99 | 489.00 | 0 | 738.99
TOTAL | 366.99 | 643.45 | 16.00 | 1026.44
(5 rows)
- Periods as columns: each column's condition is a half-open date range for one week. Any condition works in
FILTER, not only equality. - Zeros:
COALESCE(SUM(...) FILTER (...), 0)turns empty cells into 0.COUNTalready returns 0 for an empty set, so it needs noCOALESCE. - Row total: an unfiltered
SUM(amount)in the same query. It should equal the sum of the week columns, a useful check that the conditions cover every row without overlapping (article 21). - Total row:
GROUP BY ROLLUP (category)(article 20) adds a row wherecategoryis NULL, aggregating all categories.COALESCElabels it, andORDER BY GROUPING(category)puts it last.
Pivoting by position
Sometimes the columns aren't values from the data but positions: a customer's first, second and third order; the top three products in each category. Number the rows first, then pivot on the number:
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);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- Pivot by position: each customer's orders, oldest first, as columns
WITH numbered AS (
SELECT c.name, o.order_id,
ROW_NUMBER() OVER (PARTITION BY c.customer_id ORDER BY o.placed_on) AS n
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
)
SELECT name,
MAX(order_id) FILTER (WHERE n = 1) AS first_order,
MAX(order_id) FILTER (WHERE n = 2) AS second_order,
MAX(order_id) FILTER (WHERE n = 3) AS third_order
FROM numbered
GROUP BY name
ORDER BY name;
name | first_order | second_order | third_order
------------+-------------+--------------+-------------
Asha Rao | 101 | 103 |
Ben Okafor | 102 | |
Chen Wei | 104 | |
Dana Cruz | 105 | |
(4 rows)
ROW_NUMBER() (article 27) numbers each customer's orders by date, and the pivot puts number 1 in first_order, 2 in second_order, and so on. MAX just picks the single value in each cell. This turns a list of unknown length into a fixed number of columns: customers with more than three orders lose the rest, so choose a limit that suits the report, or use string_agg (article 37) to keep everything in one column.
crosstab in PostgreSQL
PostgreSQL's tablefunc extension provides crosstab, which takes a query producing (row label, column label, value) rows:
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);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- crosstab from the tablefunc extension
CREATE EXTENSION IF NOT EXISTS tablefunc;
SELECT *
FROM crosstab(
$$ SELECT category, status, SUM(amount)
FROM sales
GROUP BY category, status
ORDER BY 1, 2 $$,
$$ VALUES ('pending'), ('shipped'), ('delivered'), ('cancelled') $$
) AS ct (category text, pending numeric, shipped numeric, delivered numeric, cancelled numeric)
ORDER BY category;
category | pending | shipped | delivered | cancelled
----------+---------+---------+-----------+-----------
clothing | | 64.00 | 30.00 |
lighting | | 69.00 | 34.50 |
packs | | | 89.95 | 54.00
tents | 489.00 | 249.99 | |
(4 rows)
The second argument lists the column labels, in the order of the output columns. The AS ct (...) clause must still declare every output column and its type, because PostgreSQL needs to know a query's columns before it runs. Use the two-argument form: the one-argument crosstab(sql) fills columns in the order values arrive, so a category with no "pending" row has its "shipped" value shifted into the pending column, silently.
crosstab gives no real advantage over conditional aggregation, which is standard, easier to read and works without an extension. You'll see it in existing code.
The PIVOT operator
SQL Server and Oracle have a PIVOT clause. In SQL Server:
SELECT category, [pending], [shipped], [delivered], [cancelled]
FROM (SELECT category, status, amount FROM sales) AS src
PIVOT (SUM(amount) FOR status IN ([pending], [shipped], [delivered], [cancelled])) AS p;
And in Oracle:
SELECT *
FROM (SELECT category, status, amount FROM sales)
PIVOT (SUM(amount) FOR status IN ('pending' AS pending, 'shipped' AS shipped,
'delivered' AS delivered, 'cancelled' AS cancelled));
PIVOT groups implicitly by every column of the source not mentioned in the PIVOT clause. That's why both examples select from a subquery containing only the columns needed. Pivoting directly from a table with an order_id column would produce one row per order, not per category. It's the most common PIVOT bug.
PIVOT supports one aggregate (Oracle allows several) and an equality list, so conditional aggregation is still needed for ranges, totals and mixed aggregates. MySQL, PostgreSQL and SQLite have no PIVOT. DuckDB has a PIVOT statement that can work out the columns itself.
Dynamic pivots
Every method so far lists the columns in the query. If the values come from the data, such as a column per brand, where brands are added over time, the query has to change whenever the data does. A SQL query can't have a variable number of columns, so the solution is dynamic SQL: build the query text from the data, then run it.
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);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- A dynamic pivot: build the query text from the data, then run it with \gexec
SELECT format(
'SELECT category, %s FROM sales GROUP BY category ORDER BY category',
string_agg(format('COUNT(*) FILTER (WHERE brand = %L) AS %I', brand, lower(brand)),
', ' ORDER BY brand))
FROM (SELECT DISTINCT brand FROM sales WHERE brand IS NOT NULL) AS b
\gexec
category | alpina | kestrel | lumen | woolly
----------+--------+---------+-------+--------
clothing | 0 | 0 | 0 | 3
lighting | 0 | 0 | 2 | 0
packs | 0 | 2 | 0 | 0
tents | 2 | 0 | 0 | 0
(4 rows)
The SELECT reads the distinct brands and builds one COUNT(*) FILTER (...) per brand with string_agg, producing a complete query as text. psql's \gexec command then runs that text as a query. Two functions keep this safe:
format('%L', value)quotes a value as a literal, and%Iquotes an identifier, such as a column name. Brands come from the data, so they must never be pasted in unquoted: a brand namedx'); DROP TABLE sales; --would otherwise become part of the SQL (article 59).- Lower-casing keeps the column names simple, but two brands that differ only in case would then collide. Real code should check for that.
Outside psql, the same idea works in a stored procedure or function with EXECUTE (article 66), in SQL Server with STRING_AGG, QUOTENAME and sp_executesql, and in Oracle with EXECUTE IMMEDIATE. Often the simplest place to pivot dynamically is the application or reporting tool: fetch the long data and arrange it there. Spreadsheets, BI tools and dataframe libraries all pivot well.
A flexible alternative: JSON
If the consumer is an application, a pivot doesn't need fixed columns at all:
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);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- A flexible alternative: one JSON object per row, with whatever keys exist
SELECT category,
jsonb_object_agg(status, amount ORDER BY status) AS amount_by_status
FROM (SELECT category, status, SUM(amount) AS amount
FROM sales
GROUP BY category, status) AS t
GROUP BY category
ORDER BY category;
category | amount_by_status
----------+------------------------------------------
clothing | {"shipped": 64.00, "delivered": 30.00}
lighting | {"shipped": 69.00, "delivered": 34.50}
packs | {"cancelled": 54.00, "delivered": 89.95}
tents | {"pending": 489.00, "shipped": 249.99}
(4 rows)
jsonb_object_agg(key, value) (article 43) collects each category's statuses into one object with whatever keys exist. The query never needs to change when a new status appears, and the application reads the keys it needs.
What's current
FILTERis part of the SQL standard and supported by PostgreSQL and SQLite. MySQL, SQL Server and Oracle still needCASEinside the aggregate.- PostgreSQL 16 added the standard
JSON_OBJECTAGG, an alternative tojsonb_object_aggfor JSON pivots. - DuckDB's
PIVOTstatement can find the column values itself, an approach no mainstream server database has adopted.
Common questions
How do I pivot in MySQL or PostgreSQL, which have no PIVOT?
With conditional aggregation: GROUP BY the row label and one SUM(CASE WHEN col = 'x' THEN value END) or SUM(value) FILTER (WHERE col = 'x') per column.
Why do I get NULLs in my pivot?
No rows matched that combination. Use COALESCE(..., 0), or COUNT, which returns 0.
Why does my SQL Server PIVOT return too many rows?
PIVOT groups by every source column not used in the PIVOT clause. Select only the needed columns in a subquery first.
Can SQL generate the columns automatically? Not in one static query: the columns must be known before the query runs. Build the query dynamically, or pivot in the application.
How do I add a total row and column?
An unfiltered aggregate gives the row total, and GROUP BY ROLLUP adds the total row.
Summary
- Pivoting turns values from one column into column headings.
- The portable method is conditional aggregation:
GROUP BYthe row label, with oneFILTERorCASEaggregate per column. COALESCEgives zeros, an unfiltered aggregate gives row totals, andROLLUPadds a total row.- Pivot by position by numbering rows with
ROW_NUMBERfirst. crosstab(PostgreSQL) andPIVOT(SQL Server, Oracle) also need the columns listed.PIVOTgroups by every leftover source column.- When the columns depend on the data, generate the query dynamically, with properly quoted values, or pivot in the application.
jsonb_object_agggives a flexible pivot as JSON.
Practice questions
Write a query that shows, for each category, the number of order lines that are shipped and the number that aren't, as two columns.
Answer
SELECT category,
COUNT(*) FILTER (WHERE status = 'shipped') AS shipped,
COUNT(*) FILTER (WHERE status <> 'shipped') AS not_shipped
FROM sales
GROUP BY category
ORDER BY category;
clothing 2 and 1, lighting 1 and 1, packs 0 and 2, tents 1 and 1. COUNT gives 0, not NULL, for packs.
Rewrite SUM(amount) FILTER (WHERE status = 'pending') for a database that doesn't support FILTER.
Answer
SUM(CASE WHEN status = 'pending' THEN amount END)
Rows with another status give NULL, which SUM ignores.
A SQL Server query pivots SELECT * FROM sales with PIVOT (SUM(amount) FOR status IN (...)) and returns one row per order line instead of one per category. Why?
Answer
PIVOT groups by every source column not used in the PIVOT clause: here order_id, placed_on, category, brand and qty. Select only category, status and amount in a subquery, so category is the only grouping column.
Why is the one-argument form of crosstab risky?
Answer
It fills the output columns in the order the values arrive, without matching them to column labels. If a row label is missing a value, the later values shift left into the wrong columns. The two-argument form matches each value to its column.
Why must a dynamic pivot quote the values it turns into column names and literals?
Answer
The values come from the data, which can contain quotes or SQL. Pasting them in unquoted can break the query or allow SQL injection. format with %I for identifiers and %L for literals quotes them safely.

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.