Sub topic 7
WHERE, FILTER or HAVING?
This chapter assumes you can write SELECT, WHERE and GROUP BY queries, know what count, sum and avg do, and know how NULL behaves in comparisons. It also assumes you have seen FILTER (WHERE ...) and the CASE-inside-aggregate pattern from earlier chapters. All examples use the orders table:
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
amount numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL
);WHERE, FILTER and HAVING all remove something from a query, and beginners often swap them. They act at different stages and on different things:
- WHERE removes rows before any grouping happens.
- FILTER removes rows from a single aggregate's input, and leaves every other aggregate alone.
- HAVING removes whole groups after the aggregates have been computed.
Choosing the right one is mostly a question of what you want to disappear: a row, a row for one calculation only, or a group.
The order of evaluation
A SELECT statement is not executed in the order you write it. Conceptually, PostgreSQL processes it like this:
Three consequences follow from this order:
- A row removed by WHERE is invisible to every aggregate, including filtered ones.
- FILTER runs inside the aggregate step, so it cannot remove a group. It can only change what each aggregate sees.
- HAVING runs after aggregates exist, so it can compare them. WHERE cannot, because no aggregate has been computed yet.
PostgreSQL may reorder work internally for speed, but the result always matches this logical order.
WHERE: restrict the rows for the whole query
Use WHERE when a condition applies to every number the query produces:
SELECT
customer_id,
count(*) AS paid_orders,
sum(amount) AS paid_revenue
FROM orders
WHERE status = 'paid'
GROUP BY customer_id;Every aggregate here sees only paid orders. A customer with no paid orders does not appear in the output at all, because no rows for that customer survive to the grouping step.
WHERE is also the only one of the three that can use an index to avoid reading rows. If the condition is on an indexed column such as created_at, WHERE lets the planner skip most of the table.
FILTER: restrict the rows for one aggregate
Use FILTER when different columns of the result need different row sets:
SELECT
customer_id,
count(*) AS orders,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders
GROUP BY customer_id;Here orders counts every order for the customer, while the other two columns count only paid ones. A single WHERE could not do this, because it would shrink the input for all three columns.
This query also keeps customers who have never paid. Their group still exists, so they appear with paid_orders = 0 and paid_revenue = NULL. That difference from the WHERE version matters in reports, as the next section shows.
WHERE versus FILTER when there is only one condition
If a query has one aggregate and one condition, WHERE and FILTER can give the same numbers. The difference is which groups survive.
| Query shape | Customer with no paid orders |
|---|---|
| `WHERE status = 'paid' GROUP BY customer_id` | Absent from the result |
| `count(*) FILTER (WHERE status = 'paid') ... GROUP BY customer_id` | Present, with count 0 |
Decide which you want. A "customers and their paid totals" list that should include customers who paid nothing needs FILTER. A "who has paid" list wants WHERE.
Without GROUP BY, the situation is different. An aggregate query with no GROUP BY always returns exactly one row, even if WHERE removes every input row:
SELECT
count(*) AS paid_orders,
sum(amount) AS paid_revenue
FROM orders
WHERE status = 'no-such-status';This returns one row with paid_orders = 0 and paid_revenue = NULL. Both WHERE and FILTER behave the same way in this case.
HAVING: restrict the groups
HAVING is the filter for aggregate results. This query finds customers with at least three refunded orders:
SELECT
customer_id
FROM orders
GROUP BY customer_id
HAVING count(*) FILTER (WHERE status = 'refunded') >= 3;The aggregate count(*) FILTER (WHERE status = 'refunded') is computed once per customer. HAVING then keeps only the customers where it is at least 3. Note the division of labour: FILTER decides which rows are counted, and HAVING decides which groups are kept.
You can try to do this with WHERE alone, but it behaves differently:
SELECT
customer_id
FROM orders
WHERE status = 'refunded'
GROUP BY customer_id
HAVING count(*) >= 3;The customer list is the same. The difference appears as soon as you select anything else. In this version, every other aggregate in the SELECT list also sees only refunded rows. If you want the customer's total order count next to the refund count, you need the FILTER version.
HAVING on a plain column
PostgreSQL accepts a HAVING condition that uses only grouping columns:
SELECT customer_id, count(*)
FROM orders
GROUP BY customer_id
HAVING customer_id < 1000;This works, but WHERE is better. WHERE discards rows before grouping, so less data reaches the aggregation step. Reserve HAVING for conditions that involve an aggregate.
One query using all three
The clauses combine naturally. This report covers orders created in 2026 and lists customers with at least three refunds in that year:
SELECT
customer_id,
count(*) AS orders_2026,
count(*) FILTER (WHERE status = 'refunded') AS refunded,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue
FROM orders
WHERE created_at >= '2026-01-01'
AND created_at < '2027-01-01'
GROUP BY customer_id
HAVING count(*) FILTER (WHERE status = 'refunded') >= 3
ORDER BY refunded DESC, customer_id;Read it in evaluation order:
- WHERE keeps only 2026 orders. This condition applies to every column, so it belongs here, and it can use an index on
created_at. - GROUP BY forms one group per customer.
- Each aggregate computes its value.
orders_2026counts all rows in the group. The other two apply their own FILTER conditions. - HAVING drops customers with fewer than three refunds.
- ORDER BY sorts the result. It can use the output alias
refundedbecause it runs after the SELECT list.
The timestamp literals are interpreted in the session time zone, because created_at is timestamptz. If your report must use a fixed zone, write the bounds with an explicit offset, such as '2026-01-01 00:00:00+00'.
Choosing: a decision table
| Question | Use |
|---|---|
| Should this condition affect every number in the result? | WHERE |
| Should it affect only one aggregate column? | FILTER |
| Should it remove groups based on an aggregate value? | HAVING |
| Should groups with no matching rows still appear, with 0 or NULL? | FILTER, not WHERE |
| Is the condition on a plain column and you only need to cut rows? | WHERE, not HAVING |
A useful shortcut: if every aggregate in the query would carry the same FILTER condition, move that condition to WHERE. The query gets shorter, and the planner can use indexes and read fewer rows.
Common errors
Aggregates in WHERE
This fails:
SELECT customer_id
FROM orders
WHERE count(*) >= 3
GROUP BY customer_id;PostgreSQL reports ERROR: aggregate functions are not allowed in WHERE. The aggregate does not exist yet at the WHERE stage. Move the condition to HAVING.
Output aliases in WHERE and HAVING
Neither clause can see aliases defined in the SELECT list:
SELECT
customer_id,
count(*) FILTER (WHERE status = 'refunded') AS refunded
FROM orders
GROUP BY customer_id
HAVING refunded >= 3;This fails with column "refunded" does not exist. Repeat the expression in HAVING, as in the earlier example, or wrap the query in a subquery or common table expression (CTE) and filter in the outer query. ORDER BY is the only clause evaluated after the SELECT list that accepts aliases.
A WHERE that cancels a FILTER
Conditions combine with AND, not OR, across stages. This query always reports zero refunds:
SELECT
count(*) FILTER (WHERE status = 'refunded') AS refunded
FROM orders
WHERE status = 'paid';WHERE has already thrown away every refunded row, so FILTER has nothing to count. Whenever a query mixes WHERE and FILTER, check that the WHERE condition keeps every row that any filtered aggregate needs.
Aggregates inside FILTER
The FILTER condition is evaluated per row. It cannot contain an aggregate or a window function. Writing FILTER (WHERE amount > avg(amount)) fails with aggregate functions are not allowed in FILTER. To compare rows with a group average, compute the average in a subquery or a CTE first, then join it back.
HAVING without GROUP BY
HAVING works on a query with no GROUP BY, treating all rows as one group:
SELECT count(*) AS orders
FROM orders
HAVING count(*) > 100;If there are 100 rows or fewer, this returns zero rows, not a row containing 0. That differs from the same query without HAVING, which always returns one row.
Exercises
Exercise
A query selects customerid, count(*) AS orders and sum(amount) AS total, grouped by customerid, and uses WHERE status = 'paid'. A colleague complains that customers who only have refunded orders are missing from the report, and the report should show them with 0 paid orders. How would you change the query?
Show answer
Remove the WHERE clause and put the condition on the aggregates instead: count(*) FILTER (WHERE status = 'paid') AS paidorders, and sum(amount) FILTER (WHERE status = 'paid') AS paidtotal. Customers with no paid orders then keep their group and show 0 and NULL. Wrap the sum in coalesce(..., 0) if the report needs a zero instead of NULL.
Exercise
Write a query that returns each customer_id with their total number of orders and their number of pending orders, but only for customers who have at least 5 pending orders. Which clause holds the pending condition, and which holds the threshold?
Show answer
SELECT customerid, count() AS orders, count() FILTER (WHERE status = 'pending') AS pendingorders FROM orders GROUP BY customer_id HAVING count(*) FILTER (WHERE status = 'pending') >= 5; The pending condition is in FILTER, which limits which rows one aggregate counts. The threshold is in HAVING, which removes groups. Using WHERE status = 'pending' would make the orders column count only pending orders.
Exercise
Why does this query fail, and how do you fix it? SELECT customerid, sum(amount) AS total FROM orders GROUP BY customerid HAVING total > 1000;
Show answer
HAVING cannot refer to the output alias total, so PostgreSQL reports that the column does not exist. Repeat the expression: HAVING sum(amount) > 1000. Alternatively, put the grouped query in a subquery or CTE and filter on total in the outer query's WHERE.