DEV Community

Cover image for WHERE vs GROUP BY vs HAVING: Filtering Rows, Grouping Them, Filtering Groups
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

WHERE vs GROUP BY vs HAVING: Filtering Rows, Grouping Them, Filtering Groups

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:

  • WHERE filters rows, before any grouping.
  • GROUP BY turns the remaining rows into groups, one result row per group.
  • HAVING filters groups, after aggregates like SUM or COUNT are 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
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

The order SQL runs it in

You write SELECT first, but the database evaluates the clauses in a different logical order:

  1. FROM (and joins): take the rows of orders.
  2. WHERE: keep rows with status = 'paid'. Row 3 is dropped.
  3. GROUP BY: put the remaining rows into groups by city: Algiers (rows 1 and 4), Oran (2 and 5), Setif (6).
  4. Aggregates are computed per group: Algiers 3200, Oran 1900, Setif 300.
  5. HAVING: keep groups with SUM(amount) > 2000. Only Algiers remains.
  6. SELECT: build the output columns.
  7. ORDER BY, then LIMIT.

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;
Enter fullscreen mode Exit fullscreen mode

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) > 2000 fails. Use HAVING.
  • Row filters in HAVING. HAVING city = 'Oran' works in many databases when city is a grouped column, but it filters after all the grouping work is done. Put plain row conditions in WHERE so fewer rows are processed.
  • Using the SELECT alias in HAVING. HAVING revenue > 2000 works in MySQL but not in PostgreSQL or SQL Server, because SELECT runs after HAVING. Repeat the expression: HAVING SUM(amount) > 2000.
  • Selecting non-grouped columns without an aggregate.
  • Forgetting that COUNT(column) ignores NULLs while COUNT(*) 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 BY that category.
  • Condition on a total, count or average per group: HAVING.
  • Both kinds of condition: use both, WHERE first to reduce rows, HAVING after 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)