skip to content

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.

column =
long: GROUP BY month, status (15 rows)
one row per month and status
monthstatusn
2026-03-01cancelled18
2026-03-01delivered834
2026-03-01refunded7
2026-04-01cancelled23
2026-04-01delivered798
2026-04-01refunded9
2026-05-01cancelled27
2026-05-01delivered826
2026-05-01refunded6
2026-06-01cancelled18
2026-06-01delivered466
2026-06-01paid62
2026-06-01placed51
2026-06-01refunded7
2026-06-01shipped120
wide: GROUP BY month, a FILTER per column (4 rows)
one row per month
month
2026-03-018340187
2026-04-017980239
2026-05-018260276
2026-06-01466233187

one long row per month becomes one cell per month. 834 in march, both ways.

real output, postgres 18.6 (PGlite 0.5.12) · filter-and-pivots
pick a column of the wide table. the long rows that feed it light up: each FILTER column is the long table's rows for its status, laid side by side. june is the only month still in flight, so 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:

sqldb=shop
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;
output, from postgres 18.6
SELECT 4
monthdatedeliveredint8in_flightint8cancelledint8refundedint8
2026-03-018340187
2026-04-017980239
2026-05-018260276
2026-06-01466233187
(4 rows)

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:

aggregate =
the rows, and which aggregates count each one
idstatus
880cancelled✓··✓
1455refunded✓···
6580delivered✓✓··
7787delivered✓✓··
8219delivered✓✓··
9615delivered✓✓··
9946placed✓·✓·
postgres returned7411

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.

real output, postgres 18.6 (PGlite 0.5.12) · filter-and-pivots
Ada Lovelace's seven orders, and for each aggregate whether its FILTER is true for the row (✓). pick one: the rows it counted are tinted, the rows its FILTER kept out are struck. the bottom row is what postgres returned.

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":

spelling =
query.sql
  1. 1SELECT date_trunc('month', ordered_at)::date AS month,
  2. 2 count(*) FILTER (WHERE status = 'cancelled') AS cancelled
  3. 3FROM orders
  4. 4WHERE ordered_at >= '2026-03-01'
  5. 5GROUP BY 1
  6. 6ORDER BY 1;
the result for FILTER
monthdatecancelledint8
2026-03-0118
2026-04-0123
2026-05-0127
2026-06-0118
(4 rows)

FILTER: the condition sits right next to the aggregate. 18 cancelled orders in march.

real output, postgres 18.6 (PGlite 0.5.12) · filter-and-pivots
four spellings of "cancelled orders per month". the first three agree. the fourth counts every order, because 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).

predict the output
sql
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:

sqldb=shop
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;
output, from postgres 18.6
SELECT 3
monthdatepaid_filterint8paid_sum_caseint8
2026-04-010null
2026-05-010null
2026-06-016262
(3 rows)

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 \crosstabview turns a long result into a grid on screen.
  • crosstab() from the tablefunc extension 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:

sqldb=shop
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;
output, from postgres 18.6
SELECT 4
monthdatestatustextnint8
2026-05-01cancelled27
2026-05-01delivered826
2026-06-01cancelled18
2026-06-01delivered466
(4 rows)

(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.