FILTER and pivoting
count(*) FILTER (WHERE ...), the SUM(CASE ...) it replaced, and rows turned into columns.
- address
- everything.analytics.filter_and_pivots
- part
- part 4, windows, grouping and recursion
- chapter
- chapter 1 of 11
- reading time
- 7 min
FILTER (WHERE ...) after an aggregate makes it look at only the rows where the condition holds: count(*) FILTER (WHERE status = 'cancelled'). several of them side by side, one per value, turn rows into columns: that's a pivot.
before FILTER there was sum(CASE WHEN ... THEN 1 ELSE 0 END), which still works, and has a near twin that gives the wrong answer.
the picture
you know how GROUP BY month, status gives you a tall list (march, cancelled, 18; march, delivered, 834; ...) and the person asking wanted a table with months down the side and statuses across the top? that's the same numbers, turned. SQL doesn't have a "turn" button, but each column of the wide table is just a count with a condition on it.
think of a mail sorter's desk with a row of trays, one per status. every order from march goes past the trays, and each tray only catches its own kind. the trays are the FILTER clauses; the month is the GROUP BY.
| month | status | n |
|---|---|---|
| 2026-03-01 | cancelled | 18 |
| 2026-03-01 | delivered | 834 |
| 2026-03-01 | refunded | 7 |
| 2026-04-01 | cancelled | 23 |
| 2026-04-01 | delivered | 798 |
| 2026-04-01 | refunded | 9 |
| 2026-05-01 | cancelled | 27 |
| 2026-05-01 | delivered | 826 |
| 2026-05-01 | refunded | 6 |
| 2026-06-01 | cancelled | 18 |
| 2026-06-01 | delivered | 466 |
| 2026-06-01 | paid | 62 |
| 2026-06-01 | placed | 51 |
| 2026-06-01 | refunded | 7 |
| 2026-06-01 | shipped | 120 |
| month | ||||
|---|---|---|---|---|
| 2026-03-01 | 834 | 0 | 18 | 7 |
| 2026-04-01 | 798 | 0 | 23 | 9 |
| 2026-05-01 | 826 | 0 | 27 | 6 |
| 2026-06-01 | 466 | 233 | 18 | 7 |
one long row per month becomes one cell per month. 834 in march, both ways.
in_flight collects three statuses there and nothing anywhere else.FILTER
the FILTER clause goes right after an aggregate and takes a WHERE condition. the aggregate then sees only the rows of its group where that condition is true:
SELECT date_trunc('month', ordered_at)::date AS month,
count(*) FILTER (WHERE status = 'delivered') AS delivered,
count(*) FILTER (WHERE status IN ('placed', 'paid', 'shipped')) AS in_flight,
count(*) FILTER (WHERE status = 'cancelled') AS cancelled,
count(*) FILTER (WHERE status = 'refunded') AS refunded
FROM orders
WHERE ordered_at >= '2026-03-01'
GROUP BY 1
ORDER BY 1;| monthdate | deliveredint8 | in_flightint8 | cancelledint8 | refundedint8 |
|---|---|---|---|---|
| 2026-03-01 | 834 | 0 | 18 | 7 |
| 2026-04-01 | 798 | 0 | 23 | 9 |
| 2026-05-01 | 826 | 0 | 27 | 6 |
| 2026-06-01 | 466 | 233 | 18 | 7 |
the important word is only. the query's WHERE decides which rows exist at all (orders since march). each FILTER decides which of those rows one aggregate counts, without touching the others. every aggregate in a row can have its own:
| id | status | ||||
|---|---|---|---|---|---|
| 880 | cancelled | ✓ | · | · | ✓ |
| 1455 | refunded | ✓ | · | · | · |
| 6580 | delivered | ✓ | ✓ | · | · |
| 7787 | delivered | ✓ | ✓ | · | · |
| 8219 | delivered | ✓ | ✓ | · | · |
| 9615 | delivered | ✓ | ✓ | · | · |
| 9946 | placed | ✓ | · | ✓ | · |
| postgres returned | 7 | 4 | 1 | 1 | |
delivered: 4 of 7 rows counted, result 4. four of her orders were delivered. the cancelled, refunded and placed ones are invisible to this count, and only to this one.
FILTER works on any aggregate, not just count: sum(amount) FILTER (WHERE kind = 'purchase'), avg(price) FILTER (WHERE NOT discontinued), string_agg(name, ', ' ORDER BY name) FILTER (WHERE ...). it's in the SQL standard and in postgres since 9.4. not every engine has it, which is one reason the CASE spelling is everywhere.
the CASE spellings
before FILTER, you'd put the condition inside the aggregate, with CASE turning each row into "something" or "nothing":
- 1SELECT date_trunc('month', ordered_at)::date AS month,
- 2 count(*) FILTER (WHERE status = 'cancelled') AS cancelled
- 3FROM orders
- 4WHERE ordered_at >= '2026-03-01'
- 5GROUP BY 1
- 6ORDER BY 1;
| monthdate | cancelledint8 |
|---|---|
| 2026-03-01 | 18 |
| 2026-04-01 | 23 |
| 2026-05-01 | 27 |
| 2026-06-01 | 18 |
FILTER: the condition sits right next to the aggregate. 18 cancelled orders in march.
ELSE 0 gives count a value to count.the trap is in what each aggregate skips. sum adds the 1s and the 0s, so ELSE 0 is harmless there. count counts every value that isn't NULL, and 0 isn't NULL. leave the ELSE off and CASE gives NULL for the other rows, which count skips: correct. write ELSE 0 out of habit and count counts everything (aggregates has the NULL-skipping rule).
SELECT count(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END)
FROM orders
WHERE ordered_at >= '2026-03-01' AND ordered_at < '2026-04-01';and a FILTERed count is 0 when no row matches, while sum(CASE WHEN ... THEN 1 END) with no ELSE is NULL. that difference shows up in the empty cells of a pivot:
SELECT date_trunc('month', ordered_at)::date AS month,
count(*) FILTER (WHERE status = 'paid') AS paid_filter,
sum(CASE WHEN status = 'paid' THEN 1 END) AS paid_sum_case
FROM orders
WHERE ordered_at >= '2026-04-01'
GROUP BY 1
ORDER BY 1;| monthdate | paid_filterint8 | paid_sum_caseint8 |
|---|---|---|
| 2026-04-01 | 0 | null |
| 2026-05-01 | 0 | null |
| 2026-06-01 | 62 | 62 |
april and may had no paid orders left: FILTER says 0, the sum says NULL. if you need the sum spelling, wrap it in coalesce(..., 0).
pivots, and their one real limit
a pivot in SQL is "one FILTER per column you want". which means you have to know the columns when you write the query: a SQL query's result columns are fixed before it reads a single row. a new status next month gets no column until someone adds one.
that's the limit everyone hits, and the ways around it all move the turning somewhere else:
- write the columns out. fine when the values are a known, short list (statuses, quarters, a few regions).
- generate the query. read the distinct values first, then build the SELECT in application code or with
format()in PL/pgSQL. dynamic SQL, with all the quoting care that implies (parameters and injection). - pivot in the client. return the long table and let the spreadsheet, chart library or psql do it: psql's
\crosstabviewturns a long result into a grid on screen. - crosstab() from the
tablefuncextension takes a query for the long table and returns a wide one, but you still have to declare the output columns in the call. (it isn't in this page's browser engine.)
going the other way, wide to long (unpivot), is easier: a CROSS JOIN LATERAL (VALUES ...) that turns each row into one row per column:
WITH wide AS (
SELECT date_trunc('month', ordered_at)::date AS month,
count(*) FILTER (WHERE status = 'delivered') AS delivered,
count(*) FILTER (WHERE status = 'cancelled') AS cancelled
FROM orders
WHERE ordered_at >= '2026-05-01'
GROUP BY 1
)
SELECT w.month, v.status, v.n
FROM wide AS w
CROSS JOIN LATERAL (VALUES ('delivered', w.delivered), ('cancelled', w.cancelled)) AS v (status, n)
ORDER BY w.month, v.status;| monthdate | statustext | nint8 |
|---|---|---|
| 2026-05-01 | cancelled | 27 |
| 2026-05-01 | delivered | 826 |
| 2026-06-01 | cancelled | 18 |
| 2026-06-01 | delivered | 466 |
(LATERAL joins is why VALUES can see w.)
keylines
- FILTER (WHERE ...) narrows one aggregate to the rows where the condition holds.
- one FILTERed aggregate per column turns a long result wide: a pivot.
- count(CASE ... ELSE 0 END) counts everything. no ELSE for count, or use FILTER.
- a FILTERed count says 0 for no rows; a sum of CASE says NULL.
- result columns are fixed when the query is written, so dynamic pivots need dynamic SQL or the client.