Sub topic 8
Filtering rows with WHERE and groups with HAVING
This chapter assumes you can write SELECT ... FROM ... WHERE ... ORDER BY, know that NULL means a missing value, and have seen GROUP BY with COUNT and SUM. It covers the two places where a grouped query can filter data, what each place can see, and the mistakes that follow from mixing them up.
Two filters, two moments
A grouped query can filter at two points:
WHEREfilters individual rows before they are grouped.HAVINGfilters whole groups after they are formed and their aggregates computed.
The difference matters because a group's aggregate values exist only after grouping. WHERE runs too early to see them. HAVING runs late enough to test them.
The examples use this small table. The NULL amount is deliberate.
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
amount NUMERIC(10,2),
status VARCHAR(20) NOT NULL
);
INSERT INTO orders (order_id, customer_id, amount, status) VALUES
(1, 1, 600, 'paid'),
(2, 1, 700, 'paid'),
(3, 1, 200, 'refunded'),
(4, 2, 900, 'paid'),
(5, 2, 200, 'pending'),
(6, 3, 1500, 'paid'),
(7, 4, NULL, 'paid');The order in which clauses run
SQL is written as SELECT first, but it is evaluated in a different logical order. The database may execute the query differently for speed, but the result must match this order.
Two consequences follow from this order:
WHEREcannot use aggregate functions, because no groups exist yet.HAVINGcan use aggregate functions, because it runs after they are computed.
Using both together
This query finds customers whose paid orders total more than 1000.
SELECT customer_id,
SUM(amount) AS total_amount
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING SUM(amount) > 1000;The steps are:
WHERE status = 'paid'drops orders 3 (refunded) and 5 (pending). Five rows remain.GROUP BY customer_idforms four groups, one for each customer.SUM(amount)gives 1300 for customer 1, 900 for customer 2, 1500 for customer 3, andNULLfor customer 4.HAVING SUM(amount) > 1000keeps customers 1 and 3.
| customer_id | total_amount |
|---|---|
| 1 | 1300.00 |
| 3 | 1500.00 |
Now remove the WHERE line and keep the HAVING.
SELECT customer_id,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 1000;Customer 2 now appears with 1100, because the pending order of 200 is added to the paid 900. The WHERE clause changed which rows entered the sums, so the aggregates changed too. HAVING only decides which finished groups survive.
What each clause may contain
| Aspect | WHERE | HAVING |
|---|---|---|
| Runs | Before grouping | After grouping |
| Tests | Single rows | Whole groups |
| Aggregate functions allowed | No | Yes |
| Plain columns allowed | Any column in the table | Only grouping columns, or columns inside an aggregate |
| Works without GROUP BY | Yes | Yes, treating the whole table as one group |
| Can use indexes to skip rows | Often | Rarely, because it works on grouped output |
Aggregates in WHERE cause an error
A common first attempt is to put the total in WHERE:
SELECT customer_id, SUM(amount)
FROM orders
WHERE SUM(amount) > 1000
GROUP BY customer_id;This fails. PostgreSQL reports "aggregate functions are not allowed in WHERE", and other databases give a similar message. The fix is to move the test to HAVING.
Put row conditions in WHERE
A condition on a grouping column can legally go in either clause. These two queries return the same rows:
-- Filters first, then groups only the rows it needs
SELECT customer_id, COUNT(*) AS order_count
FROM orders
WHERE customer_id <> 4
GROUP BY customer_id;
-- Groups everything, then discards one group
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING customer_id <> 4;Prefer the first form. It has two advantages:
- Rows are removed before any grouping work. On a large table this can mean much less sorting or hashing, and an index on the filtered column can be used.
- It states the intent clearly:
WHEREdescribes which rows are in scope, andHAVINGdescribes which results are interesting.
Many optimizers rewrite the second form into the first automatically, but you should not depend on that. A condition on a non-grouped column cannot be moved this way, and it is not allowed in HAVING at all:
-- Error: status is neither grouped nor inside an aggregate
SELECT customer_id, SUM(amount)
FROM orders
GROUP BY customer_id
HAVING status = 'paid';Here status has several values within one customer's group, so the database cannot tell which one the test refers to. Use WHERE status = 'paid' instead.
Conditions that belong in HAVING
HAVING can use any aggregate, and the aggregate does not have to appear in the SELECT list.
-- Customers with at least two paid orders
SELECT customer_id
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING COUNT(*) >= 2;
-- Customers who have used more than one status
SELECT customer_id,
COUNT(DISTINCT status) AS status_count
FROM orders
GROUP BY customer_id
HAVING COUNT(DISTINCT status) > 1;
-- Customers whose largest order is at least 1000
SELECT customer_id, MAX(amount) AS largest
FROM orders
GROUP BY customer_id
HAVING MAX(amount) >= 1000;You can combine tests with AND and OR, and you can mix aggregates with grouping columns:
SELECT customer_id,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 2
AND SUM(amount) > 1000;Aliases in HAVING
You might expect to write HAVING total_amount > 1000 using the alias from SELECT. This is not portable. By the logical order, SELECT runs after HAVING, so the alias does not exist yet.
| Database | Alias in HAVING |
|---|---|
| PostgreSQL | Not allowed |
| SQL Server | Not allowed |
| Oracle | Not allowed |
| MySQL | Allowed as an extension |
| SQLite | Allowed as an extension |
Repeating the aggregate expression, as in HAVING SUM(amount) > 1000, works everywhere. The database computes the aggregate once, so the repetition costs nothing.
NULL in WHERE and HAVING
Both clauses keep a row or group only when the condition evaluates to true. If it evaluates to unknown, which is what comparing NULL gives, the row or group is dropped.
Customer 4 has a single paid order with a NULL amount. Its SUM(amount) is NULL, so HAVING SUM(amount) > 1000 is unknown and the group is removed. The same happens with HAVING SUM(amount) <= 1000. Customer 4 appears in neither result.
To keep such groups, handle the NULL explicitly:
SELECT customer_id,
SUM(amount) AS total_amount
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING SUM(amount) <= 1000
OR SUM(amount) IS NULL;The same rule applies in WHERE. WHERE amount <> 600 also removes rows where amount is NULL, which surprises many people.
HAVING without GROUP BY
HAVING is allowed without GROUP BY. The whole table, after WHERE, becomes one group, and HAVING keeps or discards that single group.
SELECT SUM(amount) AS total_amount
FROM orders
WHERE status = 'paid'
HAVING SUM(amount) > 10000;The result is either one row or no rows. In this data the paid total is 4000, so the query returns no rows. This differs from the same query without HAVING, which always returns exactly one row. It is useful as an alert-style check, but it is rare in practice.
Filtering on a value before aggregating
Sometimes you want to count only some rows in a group but still show the group. Putting the condition in WHERE removes groups that have no matching rows. Compare these:
-- Customers with no paid orders disappear entirely
SELECT customer_id, COUNT(*) AS paid_orders
FROM orders
WHERE status = 'paid'
GROUP BY customer_id;
-- Every customer stays; unpaid orders just do not count
SELECT customer_id,
SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) AS paid_orders
FROM orders
GROUP BY customer_id;The first query is a filter on the rows. The second is conditional aggregation, which keeps all groups. Choose based on whether groups with zero matches should appear.
Common mistakes
- Putting an aggregate in
WHERE. Move it toHAVING. - Putting a non-grouped, non-aggregated column in
HAVING. UseWHERE. - Putting row conditions in
HAVINGand paying for grouping rows you do not need. - Forgetting that
WHEREchanges the aggregates, whileHAVINGdoes not. - Forgetting that
NULLaggregates fail every comparison inHAVING. - Relying on aliases in
HAVING, which breaks when you move to another database.
Check your understanding
Exercise
Using the orders table above, write a query that returns each customer_id and the number of orders that are not refunded, but only for customers who have more than one such order. Which condition goes in WHERE and which in HAVING? What does it return?
Show answer
SELECT customerid, COUNT(*) AS ordercount FROM orders WHERE status <> 'refunded' GROUP BY customerid HAVING COUNT() > 1; The test status <> 'refunded' is about single rows, so it goes in WHERE. The test COUNT() > 1 is about a group, so it goes in HAVING. Only customer 2 qualifies, with 2 non-refunded orders (orders 4 and 5). Customer 1 has 2 non-refunded orders too (orders 1 and 2), so customer 1 is also returned with 2. The result is customers 1 and 2, each with ordercount 2. Customers 3 and 4 have only one order each and are removed by HAVING.
Exercise
Why does this query fail, and how do you fix it? SELECT customerid, SUM(amount) FROM orders WHERE SUM(amount) > 1000 GROUP BY customerid;
Show answer
WHERE runs before grouping, so no SUM exists yet and aggregates are not allowed there. Remove the WHERE and write HAVING SUM(amount) > 1000 after the GROUP BY clause.