Sub topic 12
Pitfalls and Limits
This chapter assumes that you know SELECT, WHERE, ORDER BY, GROUP BY, and aggregate functions such as count and sum. It also assumes that you understand that NULL means an unknown or missing value.
FILTER is useful, but it does not change the basic rules of SQL aggregation. Most mistakes come from putting the condition in the wrong place, forgetting how NULL behaves, or expecting FILTER to work on an ordinary scalar expression.
`FILTER` applies to aggregates only
The filter belongs after the aggregate function call:
SELECT
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders;This syntax is incorrect:
SELECT
sum(amount FILTER (WHERE status = 'paid'))
FROM orders;FILTER can also be used when an aggregate is acting as a window function. It cannot be attached to a scalar function such as upper, round, or coalesce by itself.
A filtered aggregate still receives rows from the query's FROM and WHERE steps. The filter then decides which of those rows reach that particular aggregate.
Do not confuse `WHERE`, `FILTER`, and `HAVING`
Use WHERE when a row should be removed before all aggregates calculate. Use FILTER when each aggregate needs its own condition. Use HAVING when a group should be removed after its aggregates have been calculated.
| Clause | Applied to | Typical purpose |
|---|---|---|
| `WHERE` | Individual input rows | Restrict the whole query |
| `FILTER` | Input rows for one aggregate | Give aggregates different conditions |
| `HAVING` | Completed groups | Keep or remove groups |
For example, this query reports paid and refunded orders only for the last day:
SELECT
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders
FROM orders
WHERE created_at >= now() - interval '1 day';The WHERE clause limits the rows available to both aggregates. Each FILTER then counts a different subset.
This query keeps only customers with at least three refunded orders:
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING count(*) FILTER (WHERE status = 'refunded') >= 3;Putting that condition in WHERE would remove non-refunded orders before grouping. That would change the meaning of every other aggregate in the query.
Watch `NULL` and empty input
count(*) returns zero when no row passes its filter. Most other aggregates return NULL when no row passes, or when every value they receive is NULL.
SELECT
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue,
coalesce(
sum(amount) FILTER (WHERE status = 'paid'),
0::numeric
) AS paid_revenue_as_zero
FROM orders;Use coalesce when a report requires a numeric zero instead of an unknown result. Be careful with percentages: protect the denominator from zero, and use a numeric value such as 100.0 when division should not use integer arithmetic.
count(*) and count(amount) are also different. The first counts every matching row. The second counts only matching rows where amount is not NULL.
Check the expression and filter separately
A filter does not make the aggregated expression non-null. In this example, a paid row with a missing amount still does not contribute to sum:
SELECT
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue,
count(*) FILTER (WHERE status = 'paid') AS paid_rows,
count(amount) FILTER (WHERE status = 'paid') AS paid_rows_with_amount
FROM orders;The three values answer different questions. Name them clearly so that a reader does not mistake rows with missing amounts for valid zero-value sales.
Limits, portability, and performance
FILTER is PostgreSQL syntax and is not supported identically by every SQL database. If a query must run on several database systems, the CASE pattern may be more portable:
SELECT
count(CASE WHEN status = 'refunded' THEN 1 END) AS refunded_orders
FROM orders;FILTER also does not guarantee a faster query. Several filtered aggregates can share one scan, but indexes, joins, grouping, and the number of rows still determine the plan. Use EXPLAIN to inspect the actual strategy rather than assuming that one written query means one physical operation.
Exercise
You need the total number of orders and the number of refunded orders, but you must keep customers with no refunds in the result. Which clause should count refunded orders, and why?
Show answer
Use count(*) FILTER (WHERE status = 'refunded'). The FILTER affects only that aggregate, so other rows remain available and customers or groups with no refunds can still appear with a count of zero.