WHERE vs HAVING and grouping
WHERE filters rows before grouping and HAVING filters groups by aggregates, and a JOIN runs even earlier, so the aggregate counts the already joined rows. A condition on a single order (paid) goes into WHERE, a condition on the total (more than 5) into HAVING. Grouping is by the unique id, not by name, because namesakes would merge, and after a one-to-many JOIN entities are counted with COUNT(DISTINCT id).
SQL · Aggregates
Find users with more than 5 orders, with their name. Where does the JOIN go and what do you group by?
A tester checks the "active buyers" segment: users with more than five paid orders, together with a name for the report. The aggregate over the orders table knows only user_id, while the name lives in users. That raises two questions: what to group by and where to filter "paid". The lesson “How does WHERE differ from HAVING?” covered the difference between WHERE and HAVING, and this one shows how it works in a query with a JOIN.
How it works and why. Logically a query goes through the steps FROM and JOIN, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. So the JOIN runs before grouping, and the aggregate counts already joined rows. Two decisions follow. The grouping key must identify the entity unambiguously, that is it must be u.id, not u.name. And the name is added to GROUP BY only so it can be displayed (in PostgreSQL and MySQL the primary key is enough, but an explicit list is portable).
What to take as the grouping key
GROUP BY u.name
Two different users named Ivan with 3 orders each merge into one group with 6 orders and enter the selection, although neither has more than 5.
GROUP BY u.id, u.name
id is unique, so groups match users. name is added only for display.
Example: from the task to the query. The task splits into three conditions. "Paid" is about a single order, so it goes in WHERE. "More than 5" is about a total per user, so it goes in HAVING. And the name is attached through a JOIN:
SELECT u.id, u.name, COUNT(*) AS orders_count
FROM orders o
JOIN users u ON u.id = o.user_id
WHERE o.status = 'paid' -- row filter
GROUP BY u.id, u.name -- key: id; name for display
HAVING COUNT(*) > 5 -- group filter
ORDER BY orders_count DESC, u.id; -- u.id breaks ties
Groups after GROUP BY and the result
| id | name | orders_count |
|---|---|---|
| 1 | Anna | 7 |
| 2 | Ivan | 3 filtered out |
| 3 | Ivan | 3 filtered out |
| 4 | Olha | 6 |
| id | name | orders_count |
|---|---|---|
| 1 | Anna | 7 |
| 4 | Olha | 6 |
In ORDER BY u.id follows the count: without it, users with the same number of orders can come back in a different order between runs, and a test comparing the list becomes unstable.
Limits and alternatives. The name can also be attached after aggregation: first count by user_id in a subquery or CTE and then join with users. That way grouping works with one narrow column and the JOIN runs over a small result:
-- aggregate by id first, then JOIN for the names
WITH busy AS (
SELECT user_id, COUNT(*) AS orders_count
FROM orders
WHERE status = 'paid'
GROUP BY user_id
HAVING COUNT(*) > 5
)
SELECT u.id, u.name, b.orders_count
FROM busy b
JOIN users u ON u.id = b.user_id
ORDER BY b.orders_count DESC, u.id;
The "paid only" filter stays in WHERE in every variant. If the join is a LEFT JOIN, a condition on the right side must not go in WHERE (see the lesson about a condition in ON and in WHERE), otherwise it turns the join into an inner one. A separate risk: one more "one-to-many" JOIN multiplies rows.
-- after a JOIN with order_items each order has several rows
SELECT o.user_id,
COUNT(*) AS item_rows, -- counts items
COUNT(DISTINCT o.id) AS orders -- counts orders
FROM orders o
JOIN order_items i ON i.order_id = o.id
GROUP BY o.user_id;
If order items are added, COUNT(*) counts items rather than orders, so the threshold "more than 5" fires too early. For the number of orders you need COUNT(DISTINCT o.id). Finally, HAVING cannot find users without orders: no groups exist for them.
-- always 0 rows: there are no groups for users without orders
SELECT user_id FROM orders
GROUP BY user_id
HAVING COUNT(*) = 0;
-- right: users without a match
SELECT u.id
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE o.id IS NULL;
Common mistakes.
- Grouping by
nameinstead ofid: namesakes merge and the numbers are distorted. - Writing the "paid" condition in
HAVINGor forgetting it: all orders are counted. - Adding a "one-to-many"
JOINand keepingCOUNT(*): join rows are counted, not entities. ORDER BYonly by the count: the order among equal values is random.- Looking for missing records through
HAVING COUNT(*) = 0: there will never be rows.
Check yourself
Two different users are named Ivan, with 3 orders each. What happens if you group by u.name and add HAVING COUNT(*) > 5?
Answer
Grouping by name merges them into one group with 6 orders, and it passes HAVING although neither user has more than 5. You must group by u.id (and add name beside it for display).
Why does SELECT user_id FROM orders GROUP BY user_id HAVING COUNT(*) = 0 never return anything? How do you find users without orders?
Answer
Groups are built only from existing rows, and a user without orders has no rows in orders, so there is no group either. You need a LEFT JOIN with an o.id IS NULL check or NOT EXISTS.
After a JOIN with order_items the number of orders per user suddenly grew. Why and what should change?
Answer
Each order now takes as many rows as it has items, and COUNT(*) counts items. For orders you need COUNT(DISTINCT o.id), or count the orders in a subquery before the join.