Three clauses, one query, and a classic error message: aggregate functions are not allowed in WHERE. The fix is easy once you see that the three clauses work at different stages:
-
WHEREfilters rows, before any grouping. -
GROUP BYturns the remaining rows into groups, one result row per group. -
HAVINGfilters groups, after aggregates likeSUMorCOUNTare computed.
One example table
orders
id | customer | city | status | amount
---+----------+---------+----------+-------
1 | Amina | Algiers | paid | 1200
2 | Karim | Oran | paid | 400
3 | Amina | Algiers | refunded | 800
4 | Sara | Algiers | paid | 2000
5 | Karim | Oran | paid | 1500
6 | Yacine | Setif | paid | 300
Question: which cities have more than 2,000 in paid revenue?
SELECT city, SUM(amount) AS revenue
FROM orders
WHERE status = 'paid'
GROUP BY city
HAVING SUM(amount) > 2000
ORDER BY revenue DESC;
The order SQL runs it in
You write SELECT first, but the database evaluates the clauses in a different logical order:
-
FROM(and joins): take the rows oforders. -
WHERE: keep rows withstatus = 'paid'. Row 3 is dropped. -
GROUP BY: put the remaining rows into groups bycity: Algiers (rows 1 and 4), Oran (2 and 5), Setif (6). - Aggregates are computed per group: Algiers 3200, Oran 1900, Setif 300.
-
HAVING: keep groups withSUM(amount) > 2000. Only Algiers remains. -
SELECT: build the output columns. -
ORDER BY, thenLIMIT.
Result: Algiers | 3200.
This order explains every rule below. WHERE runs before groups exist, so it cannot use SUM. HAVING runs after, so it can.
Side by side
| WHERE | GROUP BY | HAVING | |
|---|---|---|---|
| Works on | Individual rows | Rows, to form groups | Groups |
| Runs | Before grouping | After WHERE | After grouping |
| Can use aggregates | No | No (it defines groups) | Yes |
| Needs GROUP BY | No | It is the grouping | Usually yes |
| Uses indexes | Yes, often | Sometimes | Not directly |
| Typical use | status = 'paid' |
GROUP BY city |
HAVING COUNT(*) > 5 |
WHERE
WHERE decides which rows take part in the query at all. It can compare columns, use IN, LIKE, BETWEEN, IS NULL, subqueries, and so on. It cannot use aggregate functions, because when it runs there is nothing to aggregate yet.
WHERE is also where the database can use indexes most effectively. Filtering early means fewer rows to group, sort and sum.
GROUP BY
GROUP BY collapses rows that share the same values in the listed columns into one row per group. After grouping, each column in SELECT must either:
- appear in
GROUP BY, or - be inside an aggregate such as
SUM,COUNT,AVG,MIN,MAX.
So SELECT city, customer, SUM(amount) ... GROUP BY city is an error in PostgreSQL and SQL Server: a city has several customers, and the database does not know which one to show. (MySQL in older, non-strict modes allowed it and returned an arbitrary value; its default ONLY_FULL_GROUP_BY mode now rejects it.)
You can group by several columns (GROUP BY city, status) and by expressions (GROUP BY date_trunc('month', created_at)).
HAVING
HAVING filters the groups that GROUP BY produced, using aggregates:
-- customers with at least two paid orders
SELECT customer, COUNT(*) AS orders
FROM orders
WHERE status = 'paid'
GROUP BY customer
HAVING COUNT(*) >= 2;
Result: Karim, 2. Amina has two orders, but one was refunded and WHERE removed it before counting.
That shows the most important difference in practice: WHERE changes what is counted, HAVING changes which counts you keep. Moving a condition from one to the other can change the answer.
Common mistakes
-
Aggregates in
WHERE.WHERE SUM(amount) > 2000fails. UseHAVING. -
Row filters in
HAVING.HAVING city = 'Oran'works in many databases whencityis a grouped column, but it filters after all the grouping work is done. Put plain row conditions inWHEREso fewer rows are processed. -
Using the
SELECTalias inHAVING.HAVING revenue > 2000works in MySQL but not in PostgreSQL or SQL Server, becauseSELECTruns afterHAVING. Repeat the expression:HAVING SUM(amount) > 2000. - Selecting non-grouped columns without an aggregate.
-
Forgetting that
COUNT(column)ignores NULLs whileCOUNT(*)counts every row. - Mixing up the question. "Cities whose total including refunds is over 2,000" and "cities whose paid total is over 2,000" are different queries; decide which one you mean.
When to pick which
- Condition on a single row's value (status, date, category):
WHERE. - You want one result per category:
GROUP BYthat category. - Condition on a total, count or average per group:
HAVING. - Both kinds of condition: use both,
WHEREfirst to reduce rows,HAVINGafter to filter groups.
In short
WHERE picks the rows, GROUP BY bundles them, HAVING picks the bundles. Remember the run order (FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY) and the right place for each condition follows.
Originally published at abdeldjalilchougui.biz.
Top comments (0)