Combined review

GROUP BY and HAVING: a practical review

Combine filters, aggregates and conditions on groups without confusing the query's logical order.

30–35 minIntermediate levelFirst you need: WHERE, aggregate functions, GROUP BY and HAVING

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

Not started

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.

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 WHERE and which in HAVING.
  • 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.

StageWhat a row representsCheck question
Before groupingAn orderCan the condition be evaluated with a single row?
After groupingA statusWhat columns identify the group?
After aggregatingA summary per statusWhich 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:

Check SQL
SELECT COUNT(*) AS valid_rows
FROM orders
WHERE status <> 'cancelled';
Result of the preliminary check
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.

SQL
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;
Result on the teaching database
statusorderstotal_invoiced
shipped91818.70
  1. WHERE removes the cancelled orders before counting.
  2. GROUP BY status creates a group for each remaining status.
  3. COUNT and SUM produce a summary per group.
  4. HAVING checks 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.

SQL
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;
Categories that reach the threshold
categoryproductsaverage_price
Computers1999.00
Displays2214.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 WHERE the 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

  • WHERE filters rows before grouping.
  • HAVING filters groups after calculating aggregates.
  • Every non-aggregated column in the result must validly describe the group.

Suggested path