Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 04 / Topic 5 of 6

The FILTER clause

A report wants several conditional counts side by side — total orders, delivered, cancelled. FILTER restricts what a single aggregate sees:

SELECT count(*)                                     AS total_orders,
       count(*) FILTER (WHERE status = 'delivered') AS delivered,
       count(*) FILTER (WHERE status = 'cancelled') AS cancelled
FROM orders;
 total_orders | delivered | cancelled 
--------------+-----------+-----------
            9 |         6 |         1
(1 row)

One pass over the table, three answers. It works on any aggregate — delivered units vs cancelled units, summed in parallel:

SELECT sum(stock) FILTER (WHERE stock < 20)  AS units_in_low_stock,
       sum(stock) FILTER (WHERE stock >= 20) AS units_in_healthy_stock
FROM products;
 units_in_low_stock | units_in_healthy_stock 
--------------------+------------------------
                 35 |                    455
(1 row)

FILTER is standard SQL that Postgres implements beautifully; in databases without it you will see the equivalent spelled sum(CASE WHEN ... THEN 1 ELSE 0 END) — same idea, more noise. This clause is also the standard trick for pivoting rows into columns, which Stage 2's analytics part builds on.

🧪 Quick quiz — answer from memory, then check.

  1. What does count(*) FILTER (WHERE status = 'pending') count?
  2. WHERE, HAVING, FILTER — which filters what?
Show the answers
  1. Only the rows where status is pending — within an otherwise unfiltered query.
  2. WHERE filters rows, HAVING filters groups, FILTER filters what one aggregate sees.

Done here? The practice set for Part 4 — 7 exercises with solutions — is on the part page.

Search the guide