Sub topic 7
WHERE, FILTER or HAVING?
This chapter assumes basic SELECT, WHERE, ORDER BY, aggregate functions such as count and sum, and SQL NULL behavior. The examples use the orders table from the earlier chapters.
When a report needs a condition, PostgreSQL gives you three related choices:
| Clause | What it filters | When it acts |
|---|---|---|
| `WHERE` | Input rows for the whole query | Before grouping and aggregation |
| `FILTER` | Rows received by one aggregate | During that aggregate |
| `HAVING` | Completed groups | After aggregation |
Use WHERE for a condition shared by the whole report
WHERE removes rows before PostgreSQL groups or aggregates them. Every aggregate in the query sees only the remaining rows.
For example, this report considers only orders from the last 30 days:
SELECT
customer_id,
count(*) AS recent_orders,
sum(amount) AS recent_amount
FROM orders
WHERE created_at >= now() - interval '30 days'
GROUP BY customer_id
ORDER BY customer_id;Both count(*) and sum(amount) use the same restricted input. Customers with no recent orders do not form groups at all.
Use WHERE when an order should not participate in any part of the report. It can also reduce the number of rows that PostgreSQL must group, which can make a query cheaper.
Use FILTER for a condition that belongs to one aggregate
FILTER (WHERE ...) keeps the current group but limits the rows seen by one aggregate. Other aggregates in the same SELECT can use different conditions.
SELECT
customer_id,
count(*) AS all_orders,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
sum(amount) FILTER (WHERE status = 'refunded') AS refunded_amount
FROM orders
GROUP BY customer_id
ORDER BY customer_id;Each customer gets one group containing all their orders. The three aggregates then inspect that group separately.
This is useful when a report needs several measures based on different subsets. If you moved status = 'paid' into WHERE, refunded and other orders would disappear before all_orders and refunded_amount were calculated.
Use HAVING to filter completed groups
HAVING removes a group after PostgreSQL has computed its aggregate expressions. It is the right choice when the condition depends on a group total, count, or other aggregate result.
SELECT
customer_id,
count(*) AS order_count,
sum(amount) AS total_amount
FROM orders
GROUP BY customer_id
HAVING count(*) >= 5
ORDER BY total_amount DESC;This returns only customers with at least five orders. You cannot put count(*) >= 5 in WHERE, because WHERE runs before the groups and their counts exist.
HAVING can also test a filtered aggregate:
SELECT
customer_id,
count(*) FILTER (WHERE status = 'refunded') AS refunds
FROM orders
GROUP BY customer_id
HAVING count(*) FILTER (WHERE status = 'refunded') >= 3;The query first creates one group per customer, counts each customer’s refunded orders, and then keeps customers with at least three refunds.
Combine the clauses deliberately
A practical report often uses all three clauses:
SELECT
customer_id,
count(*) AS orders_in_period,
count(*) FILTER (WHERE status = 'paid') AS paid_orders,
sum(amount) FILTER (WHERE status = 'paid') AS paid_amount
FROM orders
WHERE created_at >= current_date - interval '90 days'
GROUP BY customer_id
HAVING count(*) FILTER (WHERE status = 'paid') > 0
ORDER BY paid_amount DESC;Here, WHERE limits the reporting period. FILTER calculates paid measures without losing other orders from the group. HAVING removes customers who had no paid orders.
A common mistake is using HAVING for a simple row condition:
SELECT customer_id, count(*)
FROM orders
GROUP BY customer_id
HAVING max(created_at) >= current_date - interval '30 days';This can be valid, but it first groups every order. If the intended meaning is “only include orders from the last 30 days,” WHERE expresses that meaning more directly and usually processes less data.
A decision rule
- Choose
WHEREwhen the condition applies to every calculation. - Choose
FILTERwhen different aggregates need different row conditions. - Choose
HAVINGwhen the condition depends on an aggregate or a completed group.
Exercise
You need each customer's total order count and refunded order count, but you want to show only customers with at least two refunded orders. Which clause belongs in each place?
Show answer
Use FILTER for the refunded count and HAVING for the group test:
SELECT customerid, count(*) AS totalorders, count() FILTER (WHERE status = 'refunded') AS refundedorders FROM orders GROUP BY customerid HAVING count() FILTER (WHERE status = 'refunded') >= 2;