GROUP BY and HAVING: a practical review
Combine filters, aggregates and conditions on groups without confusing the query's logical order.
Have a go before opening the examples
First you need: Filter rows with WHERE, Summarise data with COUNT, SUM, AVG, MIN and MAX, Create per-group summaries with GROUP BY, Filter groups with HAVING. If any of the groundwork is missing, go back to that lesson and then carry on from here.
Complete each task, predict a row and explain the decision that produces it. Results are saved per activity.
Practice
Drop a group after summarising
Summarise the non-cancelled orders by status. Return status, COUNT(*) as orders and ROUND(SUM(total),2) as amount. Keep only the groups with at least 8 orders.
Expected result: 1 row with the columns status, orders, amount, in that order. Row order does not matter.
View tables and data
Open this panel to see the full data.
The condition on status applies to orders; the count applies to groups.
Filter out cancelled orders before grouping, and the count afterwards.
The group threshold is COUNT(*) >= 8.
Solution explained
SELECT status,COUNT(*) AS orders,ROUND(SUM(total),2) AS amount FROM orders WHERE status <> 'cancelled' GROUP BY status HAVING COUNT(*) >= 8;The shipped status has 9 orders and passes; pending has 6 and is left out. WHERE and HAVING act on different units.
To finish: explain what a row represents, which requirement you checked and what would change if the rule changed.
See worked examples and checks
By the end, you will be able to
- Tell which condition belongs in
WHEREand which inHAVING. - Explain what each row represents after grouping.
- Check a query in stages before adding more clauses.
The mental model: rows first, groups afterwards
WHERE decides which rows reach the grouping. GROUP BY gathers the rows that share a value. Functions such as COUNT and SUM calculate one summary per group. Finally, HAVING keeps or discards whole groups.
Check question: if the condition can be evaluated by looking at a single original row, it usually belongs to WHERE. If it needs an aggregated result, it belongs in HAVING.
Before writing: define what each row represents
An aggregate query changes what a result row represents. The orders table has one row per order, but after GROUP BY status each row represents a status. Saying it out loud stops you selecting columns that no longer describe the group.
| Stage | What a row represents | Check question |
|---|---|---|
| Before grouping | An order | Can the condition be evaluated with a single row? |
| After grouping | A status | What columns identify the group? |
| After aggregating | A summary per status | Which calculation decides whether the group stays? |
Check the input rows first
Before building the summary, a check query confirms that the filter leaves fifteen orders:
SELECT COUNT(*) AS valid_rows
FROM orders
WHERE status <> 'cancelled';| valid_rows |
|---|
| 15 |
Example verified step by step
We want to summarise the non-cancelled orders by status and show only the statuses with at least eight orders.
SELECT status,
COUNT(*) AS orders,
ROUND(SUM(total), 2) AS total_invoiced
FROM orders
WHERE status <> 'cancelled'
GROUP BY status
HAVING COUNT(*) >= 8
ORDER BY total_invoiced DESC;| status | orders | total_invoiced |
|---|---|---|
| shipped | 9 | 1818.70 |
WHEREremoves the cancelled orders before counting.GROUP BY statuscreates a group for each remaining status.COUNTandSUMproduce a summary per group.HAVINGchecks the aggregated count and keeps the valid groups.
Do not pick arbitrary columns from the group
A result column must be aggregated, appear in GROUP BY or be functionally dependent on the grouped columns where the engine can prove it. For a portable approach, the easiest rule to check is the explicit one: group by every descriptive column you want to show.
Do not rely on a row picked at random. SQLite documents the idea of a «bare» column in aggregate queries, while MySQL with ONLY_FULL_GROUP_BY rejects many ambiguous selections. A teaching query should state which value represents the group, not depend on an engine extension.
Applying it: use the same method on categories
Going further, after INNER JOIN and relationships. Now each final row represents a category. The group filter keeps only the categories whose average price reaches 100.
SELECT c.name AS category,
COUNT(*) AS products,
ROUND(AVG(p.price), 2) AS average_price
FROM categories AS c
JOIN products AS p
ON p.category_id = c.id
GROUP BY c.id, c.name
HAVING AVG(p.price) >= 100
ORDER BY average_price DESC, category;| category | products | average_price |
|---|---|---|
| Computers | 1 | 999.00 |
| Displays | 2 | 214.00 |
The grouping uses both the id and the name, so the category's identity is explicit. HAVING uses the unrounded average; rounding is kept for presenting the result.
Common mistake: using HAVING for everything
A query that is harder to read
SELECT status, COUNT(*)
FROM orders
GROUP BY status
HAVING status <> 'cancelled';Although some engines accept non-aggregate conditions in HAVING, the filter conceptually belongs to the original rows. Putting it in WHERE expresses the intent better and avoids depending on particular extensions.
Check what you have mastered
- You can explain what a row represents before and after grouping.
- You know how to move to
WHEREthe conditions that belong to the original rows. - You do not select ambiguous columns that fail to identify the group.
- You check the input rows and the number of groups before trusting the final result.
Key takeaways
WHEREfilters rows before grouping.HAVINGfilters groups after calculating aggregates.- Every non-aggregated column in the result must validly describe the group.