Sub topic 12
Pitfalls and limits
This chapter assumes you can write GROUP BY queries and have used count, sum and avg. You should also know that NULL means "unknown" and that comparisons with it are never true. It also assumes you have met FILTER (WHERE ...) in the earlier chapters. All examples use the orders table from this tutorial.
FILTER is small and predictable, but a few mistakes recur. Most of them produce a wrong number with no error, which is worse than a failed query. The chapter groups them into silent mistakes, errors PostgreSQL reports, and limits you should plan around.
Silent mistakes that return wrong numbers
A WHERE clause that undoes your FILTER
WHERE runs before grouping and aggregation. It removes rows for every aggregate in the query, so a FILTER condition on the same column can no longer see the rows you excluded.
-- Wrong: WHERE removes refunded rows before count() ever sees them
SELECT
count(*) AS total_orders,
count(*) FILTER (WHERE status = 'refunded') AS refunded_orders
FROM orders
WHERE status = 'paid';Here refunded_orders is always 0, and total_orders counts only paid orders. If you want one aggregate restricted and another not, put the restriction in FILTER and leave it out of WHERE. Use WHERE only for conditions that every aggregate in the query shares.
WHERE also removes whole groups. With GROUP BY customer_id, a customer with no paid orders vanishes from the output if you write WHERE status = 'paid'. With FILTER, that customer stays in the output with a count of 0 and a NULL sum. Choose based on whether you want those customers listed.
CASE with ELSE 0 inside count
When you convert between the two styles, the most common mistake is adding ELSE 0 to a CASE that feeds count.
-- Wrong: count() counts every non-NULL value, and 0 is not NULL
SELECT count(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END) AS refunded_orders
FROM orders;
-- Right, using CASE without ELSE
SELECT count(CASE WHEN status = 'refunded' THEN 1 END) AS refunded_orders
FROM orders;
-- Right, using FILTER
SELECT count(*) FILTER (WHERE status = 'refunded') AS refunded_orders
FROM orders;The first query returns the total number of rows, because every row yields either 1 or 0 and count counts both. An ELSE 0 is correct only with sum, where adding 0 changes nothing. FILTER avoids this trap because there is no ELSE branch to get wrong.
Comparisons that silently drop NULLs
A row passes FILTER only when its condition is true. If the condition evaluates to NULL, the row is skipped, exactly as in WHERE. This matters for negative conditions on nullable columns.
SELECT
count(*) FILTER (WHERE s <> 'refunded') AS not_equal,
count(*) FILTER (WHERE s IS DISTINCT FROM 'refunded') AS distinct_from
FROM (VALUES ('paid'), ('refunded'), (NULL)) AS t(s);This returns 1 and 2. The NULL row never satisfies s <> 'refunded', but it does satisfy IS DISTINCT FROM. In orders, status is NOT NULL, so the plain <> is safe there. Check column nullability before you write a negative condition.
Integer division and zero denominators
count returns bigint. Dividing one bigint by another discards the fraction, so a ratio of counts comes out as 0 or 1 unless you convert one side to numeric. A filtered count can also be 0, which makes it unsafe as a denominator. The monthly report from earlier is safe only because it divides by the unfiltered count(*), which is at least 1 in every group.
SELECT
count(*) FILTER (WHERE status = 'refunded')::numeric
/ nullif(count(*) FILTER (WHERE status = 'paid'), 0) AS refunds_per_paid_order
FROM orders;nullif(x, 0) turns a zero denominator into NULL, so the result is NULL instead of a "division by zero" error. Decide whether NULL or 0 is the right display, and wrap the whole expression in coalesce if you need 0.
Empty sets return NULL for sum, not 0
count over zero matching rows returns 0. sum, avg, min, max and array_agg return NULL. This is easy to forget when a report is empty for a quiet period. Wrap the aggregate in coalesce(..., 0) for display, and don't wrap count, which already returns 0. Also avoid wrapping a column that you later pass to avg. Coalescing the inputs to 0 would change the average.
Errors PostgreSQL reports
These mistakes fail loudly. Each message tells you which rule you broke.
FILTER on a function that is not an aggregate
FILTER attaches only to aggregate functions. It cannot follow a scalar function or a plain expression.
-- ERROR: FILTER specified, but lower is not an aggregate function
SELECT lower(status) FILTER (WHERE amount > 10) FROM orders;If you need a conditional scalar expression, use CASE. If you meant to aggregate, put the aggregate on the outside:
SELECT string_agg(lower(status), ',') FILTER (WHERE amount > 10) AS statuses
FROM orders;Aggregates inside the FILTER condition
The WHERE inside FILTER is evaluated once per input row. It cannot contain an aggregate or a window function, because those need all the rows first.
-- ERROR: aggregate functions are not allowed in FILTER
SELECT count(*) FILTER (WHERE amount > avg(amount)) FROM orders;Compute the inner aggregate in a subquery and join it in:
SELECT count(*) FILTER (WHERE o.amount > a.avg_amount) AS above_average
FROM orders AS o
CROSS JOIN (SELECT avg(amount) AS avg_amount FROM orders) AS a;Wrong clause order with window functions
In a windowed aggregate, FILTER comes before OVER. Reversing them is a syntax error.
-- ERROR: syntax error at or near "FILTER"
SELECT sum(amount) OVER (PARTITION BY customer_id) FILTER (WHERE status = 'paid')
FROM orders;The correct order is aggregate(...) FILTER (WHERE ...) OVER (...), as in the running-total example from the window chapter.
FILTER on a non-aggregate window function
FILTER works only with window functions that are ordinary aggregates used with OVER, such as sum, count and avg. It does not work with ranking and offset functions.
-- ERROR: FILTER is not implemented for non-aggregate window functions
SELECT row_number() FILTER (WHERE status = 'paid')
OVER (PARTITION BY customer_id ORDER BY created_at)
FROM orders;If you need a running count of paid orders per customer, use an aggregate instead:
SELECT
id,
customer_id,
count(*) FILTER (WHERE status = 'paid')
OVER (PARTITION BY customer_id ORDER BY created_at) AS paid_so_far
FROM orders;Using a SELECT alias in HAVING or WHERE
You cannot refer to an output alias such as refunded_orders in HAVING, WHERE or another select-list item. Repeat the expression, or wrap the query in a subquery or CTE and filter on the alias outside. The HAVING count(*) FILTER (WHERE status = 'refunded') >= 3 example from the earlier chapter repeats the expression for this reason.
Limits to plan around
Windowed filters still return a row for every input row
A filtered window aggregate does not remove rows. It only changes what the aggregate adds up. A refunded order still appears in the output, with the running paid total as it stood at that point. Before a customer's first paid order, the running sum is NULL. If you want output rows only for paid orders, that is a WHERE job, applied in a subquery or CTE before the window runs.
Also remember that ORDER BY inside OVER uses a default frame that includes peer rows. Orders with identical created_at values receive the same running total.
FILTER does not skip work
FILTER does not make the scan cheaper. PostgreSQL still reads every row that survives WHERE, and it evaluates each filter condition for each row. The gain is that one scan replaces several, not that any scan is shortened. Two consequences follow:
- If every aggregate in the query shares a condition, move it into
WHERE. OnlyWHEREcan use an index to avoid reading rows at all. - If you need a single filtered count over a small slice of a very large table, a plain
WHEREquery that can use an index or a partial index is often faster than a full scan withFILTER.
Run EXPLAIN (ANALYZE) on both forms to see which one wins on your data. Don't assume.
Portability
FILTER is part of the SQL standard and has been in PostgreSQL since version 9.4. SQLite supports it from version 3.30. As of this writing, MySQL and SQL Server do not support it. If the query must run on those systems, or on an unknown mix of databases, write the CASE form. It works everywhere, as long as you avoid ELSE 0 with count.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| Filtered count is always 0 | `WHERE` removed those rows first | Move the condition from `WHERE` into `FILTER` |
| `count(CASE ...)` equals the row count | `ELSE 0` is counted | Drop the `ELSE`, or use `FILTER` |
| `sum` shows `NULL` | No row passed the filter | `coalesce(sum(...) FILTER (...), 0)` |
| Ratio shows 0 or 1 | Integer division | Cast to `numeric`, or multiply by `100.0` |
| "division by zero" | Filtered count used as denominator | `nullif(denominator, 0)` |
| "not an aggregate function" | `FILTER` on a scalar or ranking function | Use `CASE`, or aggregate on the outside |
| "aggregate functions are not allowed in FILTER" | Aggregate inside the condition | Compute it in a subquery and join |
| Rows with `NULL` missing from a `<>` filter | Three-valued logic | Use `IS DISTINCT FROM` |
The next diagram gives a rough order in which to check an unexpected result.
Exercises
Exercise
A colleague writes SELECT count(*) AS orders, count(*) FILTER (WHERE status = 'refunded') AS refunded FROM orders WHERE status IN ('paid', 'refunded'); and asks why orders is lower than the table's row count. They also ask whether refunded is correct. What do you tell them?
Show answer
orders is lower because WHERE drops every row whose status is neither 'paid' nor 'refunded', such as 'pending', before any aggregate runs. refunded is correct, because refunded rows pass the WHERE. If they want the count of all orders, they must remove that WHERE clause and move any restriction into FILTER.
Exercise
Write a query that returns, for each customer, the number of paid orders so far on each order row, and explain why row_number() FILTER (WHERE status = 'paid') OVER (...) cannot do this.
Show answer
Use SELECT id, customer_id, count(*) FILTER (WHERE status = 'paid') OVER (PARTITION BY customer_id ORDER BY created_at) AS paid_so_far FROM orders;. row_number() is not an aggregate function, and PostgreSQL rejects FILTER on non-aggregate window functions with "FILTER is not implemented for non-aggregate window functions". count(*) is an aggregate used as a window function, so it accepts FILTER.
Exercise
A report needs refunded / paid per month as a decimal. Some months have no paid orders. Which three problems can occur if you write count(*) FILTER (WHERE status = 'refunded') / count(*) FILTER (WHERE status = 'paid'), and what is the safe form?
Show answer
The division is integer division, so fractions are lost. A month with zero paid orders raises "division by zero". Separately, a result of NULL or 0 for a no-paid-orders month needs a deliberate choice. The safe form is count(*) FILTER (WHERE status = 'refunded')::numeric / nullif(count(*) FILTER (WHERE status = 'paid'), 0), wrapped in coalesce(..., 0) if the report should show 0 instead of NULL.