In this article
PostgreSQL has no PIVOT keyword, but you can still turn rows into columns in three ways: conditional aggregation with FILTER, the crosstab() function from the tablefunc extension, or the \crosstabview command in psql. For most reports the first one is the best choice: it is plain SQL, needs no extension, and handles missing values correctly.
This guide builds one small sales table and pivots it with every method, with the real output after each query. You will also see the classic crosstab() trap that silently puts numbers in the wrong column, how to pivot when you do not know the column names in advance, and how to unpivot columns back into rows.
What pivoting means
Pivoting takes values that are stored down a column and spreads them across the page as separate columns. A sales table stores one row per sale with a quarter column. A manager wants one row per region with Q1, Q2, Q3 and Q4 side by side. That reshaping is a pivot.
SQL needs to know every output column when the query is planned. That is why PostgreSQL cannot create columns on the fly from data, and why every method below makes you name the columns, either in the query or by generating the query first.
| Method | Needs extension | Missing values | Best for |
|---|---|---|---|
| sum(...) FILTER (WHERE ...) | No | Correct (NULL) | Most reports, views, application queries |
| sum(CASE WHEN ...) | No | Correct | SQL that must also run on other databases |
| crosstab(source, categories) | tablefunc | Correct (NULL) | Many columns from a pre-aggregated query |
| crosstab(source) one argument | tablefunc | Values shift left | Only when no row has gaps |
| \crosstabview | No (psql only) | Empty cell | Quick looks at data in the terminal |
Sample setup
Create a scratch database and this table to follow along. Note the gaps: South has no Q2 sales and West has nothing in Q1 or Q3. North and West also have more than one sale in the same quarter, so the pivot has to add them up.
CREATE TABLE sales (
sale_id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
region text NOT NULL,
quarter text NOT NULL,
amount numeric(10,2) NOT NULL
);
INSERT INTO sales (region, quarter, amount) VALUES
('North', 'Q1', 1200.00), ('North', 'Q1', 300.00),
('North', 'Q2', 950.00), ('North', 'Q3', 1100.00),
('North', 'Q4', 1400.00),
('South', 'Q1', 800.00), ('South', 'Q3', 700.00),
('South', 'Q4', 650.00),
('West', 'Q2', 500.00), ('West', 'Q2', 250.00),
('West', 'Q4', 900.00);Here is the data in its normal, long shape, one row per region and quarter:
SELECT region, quarter, sum(amount) AS total
FROM sales
GROUP BY region, quarter
ORDER BY region, quarter; region | quarter | total
--------+---------+---------
North | Q1 | 1500.00
North | Q2 | 950.00
North | Q3 | 1100.00
North | Q4 | 1400.00
South | Q1 | 800.00
South | Q3 | 700.00
South | Q4 | 650.00
West | Q2 | 750.00
West | Q4 | 900.00
(9 rows)Nine rows, and three of the twelve region and quarter combinations are missing. The goal is three rows with four quarter columns.
Method 1: pivot with FILTER (recommended)
An aggregate with a FILTER clause only sees the rows that match its condition. The PostgreSQL documentation puts it simply: only the input rows for which the filter clause evaluates to true are fed to the aggregate function, and the other rows are discarded. So you write one aggregate per output column, each filtered to one quarter, and group by the row label.
SELECT region,
sum(amount) FILTER (WHERE quarter = 'Q1') AS q1,
sum(amount) FILTER (WHERE quarter = 'Q2') AS q2,
sum(amount) FILTER (WHERE quarter = 'Q3') AS q3,
sum(amount) FILTER (WHERE quarter = 'Q4') AS q4,
sum(amount) AS year_total
FROM sales
GROUP BY region
ORDER BY region; region | q1 | q2 | q3 | q4 | year_total
--------+---------+--------+---------+---------+------------
North | 1500.00 | 950.00 | 1100.00 | 1400.00 | 4950.00
South | 800.00 | | 700.00 | 650.00 | 2150.00
West | | 750.00 | | 900.00 | 1650.00
(3 rows)Each region is one row, the two North Q1 sales were added into 1500.00, and every gap is in the right column. The empty cells are NULL, because sum of no rows returns NULL, not zero. A total column costs nothing extra: it is just another aggregate without a filter.
Show 0 instead of NULL
Reports usually want 0 in the empty cells. Wrap each aggregate in coalesce, which the documentation suggests for exactly this case:
SELECT region,
coalesce(sum(amount) FILTER (WHERE quarter = 'Q1'), 0) AS q1,
coalesce(sum(amount) FILTER (WHERE quarter = 'Q2'), 0) AS q2,
coalesce(sum(amount) FILTER (WHERE quarter = 'Q3'), 0) AS q3,
coalesce(sum(amount) FILTER (WHERE quarter = 'Q4'), 0) AS q4
FROM sales
GROUP BY region
ORDER BY region; region | q1 | q2 | q3 | q4
--------+---------+--------+---------+---------
North | 1500.00 | 950.00 | 1100.00 | 1400.00
South | 800.00 | 0 | 700.00 | 650.00
West | 0 | 750.00 | 0 | 900.00
(3 rows)The zeros print as 0 rather than 0.00 because the literal 0 has no decimal places. Use 0.00 in the coalesce if the display matters.
The CASE version for portable SQL
Before FILTER existed, people wrote the same pivot with CASE inside the aggregate. It gives the same result and works on almost every database, so it is useful when the query must also run on Oracle or MySQL:
SELECT region,
sum(CASE WHEN quarter = 'Q1' THEN amount ELSE 0 END) AS q1,
sum(CASE WHEN quarter = 'Q2' THEN amount ELSE 0 END) AS q2,
sum(CASE WHEN quarter = 'Q3' THEN amount ELSE 0 END) AS q3,
sum(CASE WHEN quarter = 'Q4' THEN amount ELSE 0 END) AS q4
FROM sales
GROUP BY region
ORDER BY region; region | q1 | q2 | q3 | q4
--------+---------+--------+---------+---------
North | 1500.00 | 950.00 | 1100.00 | 1400.00
South | 800.00 | 0 | 700.00 | 650.00
West | 0 | 750.00 | 0 | 900.00
(3 rows)In PostgreSQL, prefer FILTER: the condition sits apart from the value, so the query is easier to read, and it works with any aggregate, including count(*).
Different aggregates per column
Nothing forces every column to use the same function or the same condition. Here one query counts orders per half year and finds the largest Q4 sale:
SELECT region,
count(*) FILTER (WHERE quarter IN ('Q1','Q2')) AS h1_orders,
count(*) FILTER (WHERE quarter IN ('Q3','Q4')) AS h2_orders,
max(amount) FILTER (WHERE quarter = 'Q4') AS biggest_q4_sale
FROM sales
GROUP BY region
ORDER BY region; region | h1_orders | h2_orders | biggest_q4_sale
--------+-----------+-----------+-----------------
North | 3 | 2 | 1400.00
South | 1 | 2 | 650.00
West | 2 | 1 | 900.00
(3 rows)Note that count returns 0, not NULL, when no rows match. It is the one aggregate in the list that never returns NULL for an empty group.
Add a grand total row
GROUP BY ROLLUP (region) adds one extra row that aggregates all regions. In that row region is NULL, so give it a label with coalesce and sort it last with GROUPING(region), which returns 1 for the rollup row and 0 for the others:
SELECT coalesce(region, 'All regions') AS region,
sum(amount) FILTER (WHERE quarter = 'Q1') AS q1,
sum(amount) FILTER (WHERE quarter = 'Q2') AS q2,
sum(amount) FILTER (WHERE quarter = 'Q3') AS q3,
sum(amount) FILTER (WHERE quarter = 'Q4') AS q4
FROM sales
GROUP BY ROLLUP (region)
ORDER BY GROUPING(region), region; region | q1 | q2 | q3 | q4
-------------+---------+---------+---------+---------
North | 1500.00 | 950.00 | 1100.00 | 1400.00
South | 800.00 | | 700.00 | 650.00
West | | 750.00 | | 900.00
All regions | 2300.00 | 1700.00 | 1800.00 | 2950.00
(4 rows)Method 2: pivot with crosstab() from tablefunc
crosstab() is a function in the tablefunc extension, which ships with PostgreSQL as a contrib module. On Ubuntu with the PGDG packages it is already installed with postgresql-18; you only need to enable it in each database where you use it. The module is marked trusted, so a non-superuser with CREATE privilege on the database can enable it.
CREATE EXTENSION IF NOT EXISTS tablefunc;
\dx tablefuncCREATE EXTENSION
List of installed extensions
Name | Version | Schema | Description
-----------+---------+--------+------------------------------------------------------------
tablefunc | 1.0 | public | functions that manipulate whole tables, including crosstab
(1 row)crosstab() takes your query as a text string and returns setof record, so you must describe the output columns yourself in an AS ct(...) list after the call. The source query must return three columns: the row label, the category and the value.
The one-argument trap
The simplest form, crosstab(source_sql), looks like it works. Run it on our data:
SELECT *
FROM crosstab(
$SELECT region, quarter, sum(amount)
FROM sales
GROUP BY region, quarter
ORDER BY 1, 2$
) AS ct(region text, q1 numeric, q2 numeric, q3 numeric, q4 numeric); region | q1 | q2 | q3 | q4
--------+---------+--------+---------+---------
North | 1500.00 | 950.00 | 1100.00 | 1400.00
South | 800.00 | 700.00 | 650.00 |
West | 750.00 | 900.00 | |
(3 rows)North is right, but South's Q3 sales (700.00) now sit under q2, and West's Q2 sales sit under q1. No error, just wrong numbers. The documentation explains why: this form ignores the category column completely and fills the value columns left to right with whatever rows each group has. If a group has fewer rows than output columns, the extra columns become NULL.
The correct two-argument form
crosstab(source_sql, category_sql) takes a second query that lists the categories, one per output column, in the order of your column list. Now each value goes to the column whose category matches, and missing categories become NULL:
SELECT *
FROM crosstab(
$SELECT region, quarter, sum(amount)
FROM sales
GROUP BY region, quarter
ORDER BY 1$,
$VALUES ('Q1'), ('Q2'), ('Q3'), ('Q4')$
) AS ct(region text, q1 numeric, q2 numeric, q3 numeric, q4 numeric); region | q1 | q2 | q3 | q4
--------+---------+--------+---------+---------
North | 1500.00 | 950.00 | 1100.00 | 1400.00
South | 800.00 | | 700.00 | 650.00
West | | 750.00 | | 900.00
(3 rows)This matches the FILTER result. The rules from the documentation that matter in practice:
- The source query needs
ORDER BY 1so all rows for one region arrive together. Rows for the same label that are not next to each other produce separate output rows. - Aggregate in the source query. crosstab() does not add values up; give it one value per label and category.
- The category query must return exactly one column, at least one row and no duplicate values.
- The value columns in the AS list must have the type of the value column, and there must be exactly as many of them as the category query returns rows, in the same order.
- A category that is not in the category list is silently ignored.
Dollar quoting ($ ... $) keeps the inner queries readable. With normal single quotes you would have to double every quote inside them, as in ''Q1''.
Method 3: \crosstabview in psql
When you only want to look at a pivot in the terminal, psql can do it with no SQL changes. Write a normal query that returns three columns and end it with \crosstabview instead of a semicolon. The first column becomes the row header and the second becomes the column header:
SELECT region, quarter, sum(amount) AS total
FROM sales
GROUP BY region, quarter
ORDER BY region, quarter
\crosstabview region | Q1 | Q2 | Q3 | Q4
--------+---------+--------+---------+---------
North | 1500.00 | 950.00 | 1100.00 | 1400.00
South | 800.00 | | 700.00 | 650.00
West | | 750.00 | | 900.00
(3 rows)Swap the first two columns and you get the transposed view, with one row per quarter and one column per region:
SELECT quarter, region, sum(amount) AS total
FROM sales
GROUP BY region, quarter
ORDER BY 1, 2
\crosstabview quarter | North | South | West
---------+---------+--------+--------
Q1 | 1500.00 | 800.00 |
Q2 | 950.00 | | 750.00
Q3 | 1100.00 | 700.00 |
Q4 | 1400.00 | 650.00 | 900.00
(4 rows)The column headers come from the data, so \crosstabview is the only method here that picks up new categories automatically. The catch is that it is a psql display feature: an application, a view or another client never sees these columns. If two rows land in the same cell, psql refuses, so aggregate first. Without the GROUP BY:
\crosstabview: query result contains multiple data values for row "North", column "Q1"The psql commands guide covers more meta-commands like this one.
Dynamic pivot: when you do not know the columns
If the categories change (new products, new months), hard-coding columns means editing the query each time. Because SQL needs the columns at planning time, the answer is two steps: first generate the pivot query from the data, then run it. string_agg builds one FILTER expression per distinct category, and format with %L (a quoted literal) and %I (a quoted identifier) keeps the generated SQL safe from odd values:
SELECT format(
'SELECT region, %s FROM sales GROUP BY region ORDER BY region',
string_agg(format('sum(amount) FILTER (WHERE quarter = %L) AS %I',
quarter, lower(quarter)), ', ' ORDER BY quarter)
) AS pivot_sql
FROM (SELECT DISTINCT quarter FROM sales) AS q; SELECT region, sum(amount) FILTER (WHERE quarter = 'Q1') AS q1, sum(amount) FILTER (WHERE quarter = 'Q2') AS q2, sum(amount) FILTER (WHERE quarter = 'Q3') AS q3, sum(amount) FILTER (WHERE quarter = 'Q4') AS q4 FROM sales GROUP BY region ORDER BY region
(1 row)In psql, end the same query with \gexec instead of a semicolon. psql runs each value in the result as a statement, so you get the pivot directly:
region | q1 | q2 | q3 | q4
--------+---------+--------+---------+---------
North | 1500.00 | 950.00 | 1100.00 | 1400.00
South | 800.00 | | 700.00 | 650.00
West | | 750.00 | | 900.00
(3 rows)In application code, run the first query, read the string, and execute it as a second statement. Inside PL/pgSQL you can RETURN QUERY EXECUTE it, but a function still has to declare its output columns, which defeats the purpose. A common alternative is to return one jsonb object per row instead of real columns, which any client can read:
SELECT region,
jsonb_object_agg(quarter, total ORDER BY quarter) AS by_quarter
FROM (SELECT region, quarter, sum(amount) AS total
FROM sales GROUP BY region, quarter) AS t
GROUP BY region
ORDER BY region; region | by_quarter
--------+-------------------------------------------------------------
North | {"Q1": 1500.00, "Q2": 950.00, "Q3": 1100.00, "Q4": 1400.00}
South | {"Q1": 800.00, "Q3": 700.00, "Q4": 650.00}
West | {"Q2": 750.00, "Q4": 900.00}
(3 rows)Missing quarters are simply absent from the object. See PostgreSQL JSONB queries for reading values back out.
Unpivot: columns back to rows
The reverse job, turning q1..q4 columns into rows, comes up when you load a spreadsheet-shaped table. PostgreSQL has no UNPIVOT keyword either, but a LATERAL join to a VALUES list does it cleanly. First make a wide table from our pivot:
CREATE TABLE sales_wide AS
SELECT region,
sum(amount) FILTER (WHERE quarter = 'Q1') AS q1,
sum(amount) FILTER (WHERE quarter = 'Q2') AS q2,
sum(amount) FILTER (WHERE quarter = 'Q3') AS q3,
sum(amount) FILTER (WHERE quarter = 'Q4') AS q4
FROM sales
GROUP BY region;SELECT 3Now each wide row joins to a four-row VALUES list built from its own columns:
SELECT w.region, v.quarter, v.amount
FROM sales_wide AS w
CROSS JOIN LATERAL (VALUES ('Q1', w.q1),
('Q2', w.q2),
('Q3', w.q3),
('Q4', w.q4)) AS v(quarter, amount)
WHERE v.amount IS NOT NULL
ORDER BY w.region, v.quarter; region | quarter | amount
--------+---------+---------
North | Q1 | 1500.00
North | Q2 | 950.00
North | Q3 | 1100.00
North | Q4 | 1400.00
South | Q1 | 800.00
South | Q3 | 700.00
South | Q4 | 650.00
West | Q2 | 750.00
West | Q4 | 900.00
(9 rows)We are back to the nine long rows from the start. LATERAL lets the VALUES list refer to columns of the row on its left, and the WHERE clause drops the NULL cells. Remove it if you want a row for every quarter.
Common mistakes
ERROR: function crosstab(unknown, unknown) does not exist
The tablefunc extension is not enabled in this database (it is per database, not per server), or it is installed in a schema that is not on your search_path. Fix it with CREATE EXTENSION tablefunc; in the database you are connected to.
ERROR: function crosstab(unknown, unknown) does not exist
LINE 1: SELECT * FROM crosstab('select 1','select 1') AS ct(a int, b...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.ERROR: a column definition list is required
ERROR: a column definition list is required for functions returning "record"You called crosstab() without the AS ct(column type, ...) list. Add it after the closing parenthesis.
ERROR: invalid return type
ERROR: invalid return type
DETAIL: Query-specified return tuple has 4 columns but crosstab returns 5.The category query returned four categories, so crosstab produces one label column plus four value columns, but the AS list only had four columns in total. Make the counts match.
ERROR: duplicate category name
Your category query returned the same value twice, for example SELECT quarter FROM sales without DISTINCT. Use SELECT DISTINCT quarter FROM sales ORDER BY 1 or a fixed VALUES list.
Wrong value type in the column list
Declaring q1 int for numeric values fails with invalid input syntax for type integer: "1500.00". Declare the value columns with the same type the source query returns, or cast in the source query.
Not aggregating before pivoting
With FILTER, forgetting GROUP BY gives an error you will notice. With crosstab() and repeated rows per label and category, the second-argument form keeps only one of them, so totals are silently too small. Always GROUP BY label and category in the source query.
SELECT * FROM crosstab(
$SELECT region, quarter, amount FROM sales ORDER BY 1$,
$VALUES ('Q1'), ('Q2'), ('Q3'), ('Q4')$
) AS ct(region text, q1 numeric, q2 numeric, q3 numeric, q4 numeric); region | q1 | q2 | q3 | q4
--------+--------+--------+---------+---------
North | 300.00 | 950.00 | 1100.00 | 1400.00
South | 800.00 | | 700.00 | 650.00
West | | 250.00 | | 900.00
(3 rows)North Q1 should be 1500.00 and West Q2 should be 750.00. Each cell kept just one of the raw sales, and nothing warned about it.
Performance tips
- A FILTER pivot reads the table once. All the filtered aggregates are computed in the same pass;
EXPLAINshows a singleHashAggregateover oneSeq Scan on sales, however many columns you add. - Put a WHERE clause on the outer query (for example one year of data) so the scan only reads the rows you need. An index on that filter column helps here, not on the category column.
- crosstab() runs your source query and then reshapes the result, so its cost is the cost of the source query. It is rarely faster than FILTER for the same pivot.
- For dashboards that read the same pivot often, store it in a materialized view and refresh it on a schedule instead of pivoting raw rows on every page load.
Frequently asked questions
Does PostgreSQL have a PIVOT function?
No. PostgreSQL has no PIVOT or UNPIVOT clause like SQL Server or Oracle. Use aggregates with FILTER, the crosstab() function from the tablefunc extension, or \crosstabview in psql.
How do I pivot rows to columns without crosstab?
Group by the row label and write one aggregate per output column with a filter, for example sum(amount) FILTER (WHERE quarter = 'Q1') AS q1. It needs no extension and handles missing categories correctly.
How do I create a pivot with dynamic columns in PostgreSQL?
A single SQL statement cannot do it, because the columns must be known before the query runs. Generate the pivot SQL with string_agg and format from the distinct categories, then execute it (\gexec in psql, or a second call from your application). Or return a jsonb_object_agg column instead of real columns.
Why does crosstab put values in the wrong columns?
You are using the one-argument form on data with gaps. It ignores the category and fills columns left to right. Switch to crosstab(source_sql, category_sql) with a category list in the same order as your output columns.
How do I show 0 instead of NULL in a pivot?
Wrap each column in coalesce(..., 0). With crosstab(), use coalesce(q1, 0) in the outer SELECT instead of SELECT *.
Summary
- PostgreSQL has no PIVOT keyword; you name the output columns yourself.
- Default choice: sum(...) FILTER (WHERE ...) per column with GROUP BY on the row label.
- Wrap columns in coalesce(..., 0) when the report needs zeros instead of NULL.
- With crosstab(), always use the two-argument form and ORDER BY 1 in the source query.
- Aggregate in the source query; crosstab() does not add values up.
- Use \crosstabview for quick terminal pivots and \gexec or generated SQL for dynamic columns.
- Unpivot with CROSS JOIN LATERAL (VALUES ...).