Nishaglobal Education logo

GROUP BY and HAVING: summaries for each group

Use SQL GROUP BY to get one summary row per group (per country, category or status), filter groups with HAVING, and learn the order in which SQL runs each clause.

Lesson 7 of 1230 minQuiz: 4 questions

🎯 By the end of this lesson you will be able to:

  • Produce one summary row per group with GROUP BY
  • Filter groups with HAVING, and explain how it differs from WHERE
  • Describe the order in which a database works through a query
Outline
  1. What you'll learn and why it matters
  2. One row per group
  3. Sorting groups
  4. Filtering groups with HAVING
  5. How a database works through a query
  6. Practice
  7. Common mistakes
  8. Recap
  9. Quiz
  10. Mark lesson complete

What you'll learn and why it matters

The last lesson answered “how many orders?”. Business questions are usually “how many orders per status?”, “revenue per category?”, “customers per country?”. GROUP BY splits rows into groups and runs the aggregate once for each group. It is the single most powerful idea in reporting.

One row per group

SQL
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status;

Result: 3 rows

Query result
statusorders
cancelled2
delivered10
shipped3
6 example ordersorder_idstatus1delivered2cancelled3delivered4shipped5delivered6shippedGROUP BY statusputs rows with thesame status togetherdeliveredorders 1, 3, 5shippedorders 4, 6cancelledorders 2COUNT(*) per groupstatusorderscancelled1delivered3shipped2
GROUP BY sorts the rows into piles that share the same value, then the aggregate summarises each pile into one row.

The database collects all rows with the same status into a group, then counts each group. Three different statuses means three result rows, and 2 + 10 + 3 = 15 orders in total.

You can calculate several aggregates per group:

SQL
SELECT category, COUNT(*) AS products, MIN(price) AS cheapest, MAX(price) AS dearest
FROM products
GROUP BY category;

Result: 4 rows

Query result
categoryproductscheapestdearest
Books2350450
Electronics22991200
Home2249399
Stationery290120

Sorting groups

Sort by the aggregate's alias to rank the groups. A second sort column keeps ties in a predictable order:

SQL
SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country
ORDER BY customers DESC, country;

Result: 7 rows

Query result
countrycustomers
India4
Australia1
Canada1
Ghana1
Singapore1
UAE1
UK1

Filtering groups with HAVING

WHERE filters rows before grouping. HAVING filters groups after the aggregates are calculated, so it can use them:

SQL
SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country
HAVING COUNT(*) > 1;

Result: 1 row

Query result
countrycustomers
India4

You can use both in one query. Which customers bought at least 3 items, not counting cancelled orders?

SQL
SELECT customer_id, SUM(quantity) AS items
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
HAVING SUM(quantity) >= 3
ORDER BY items DESC, customer_id;

Result: 4 rows

Query result
customer_iditems
86
15
33
43
ClauseFiltersCan use aggregates?In this query
WHERErows, before groupingNodrops the 2 cancelled orders
HAVINGgroups, after groupingYesdrops customers with fewer than 3 items

How a database works through a query

You write a query starting with SELECT, but the database runs it in a different order. Knowing this order explains most SQL rules:

1FROMpick the table(s)2WHEREkeep matching rows3GROUP BYmake groups4HAVINGkeep matching groups5SELECTchoose columns, make aliases6ORDER BYsort the result7LIMITkeep the first N rows
The order a database works through a query: FROM picks the table, WHERE filters rows, GROUP BY makes groups, HAVING filters groups, SELECT picks columns, ORDER BY sorts and LIMIT cuts.
StepClauseConsequence
1FROMStart with the table's rows
2WHERERuns before grouping, so it cannot use COUNT or SUM
3GROUP BYRows become groups
4HAVINGCan use aggregates, because groups now exist
5SELECTAliases are created here...
6ORDER BY...so ORDER BY can use an alias such as items
7LIMITCuts the final sorted result

Practice

Guided exercise

Orders per month

Count the orders in each month. The first 7 characters of order_date are the year and month, and substr(order_date, 1, 7) gives you them.

  1. Select substr(order_date, 1, 7) AS month and COUNT(*) AS orders.
  2. Group by month.
  3. Run it and check the counts add up to 15.
Show the solution
Solution
SELECT substr(order_date, 1, 7) AS month, COUNT(*) AS orders
FROM orders
GROUP BY month;

Result: 2 rows

Query result
monthorders
2025-0910
2025-105

How to get there: substr(text, start, length) takes part of a string, here 2025-09 from 2025-09-01. SQLite lets you group by the alias; in some databases you repeat the expression instead: GROUP BY substr(order_date, 1, 7).

Your turn

Most popular products

Show each product_id and how many times it was ordered (call it times_ordered), most ordered first. Break ties by product id.

Show the solution
Solution
SELECT product_id, COUNT(*) AS times_ordered
FROM orders
GROUP BY product_id
ORDER BY times_ordered DESC, product_id;

Result: 7 rows

Query result
product_idtimes_ordered
33
12
22
42
52
62
72

How to get there: Product 3 (the Python book) was ordered 3 times. Product 8 is missing because it was never ordered: GROUP BY can only make groups from rows that exist. Lesson 10 shows how to include it with a count of 0.

Common mistakes

Selecting a column that is not grouped or aggregated

You see: An error in most databases (must appear in the GROUP BY clause); a misleading value in SQLite

Fix: Add the column to GROUP BY, or wrap it in an aggregate.

Using WHERE for an aggregate condition

You see: misuse of aggregate: COUNT()

Fix: Move the condition to HAVING.

Using HAVING for a plain row filter

You see: Works, but is slower and confusing

Fix: Filter rows with WHERE; keep HAVING for aggregate conditions.

Forgetting ORDER BY on grouped results

You see: Groups in an unexpected order

Fix: Add ORDER BY with a tie-breaker.

Recap

  • GROUP BY column makes one result row per different value, with aggregates calculated per group.
  • Every selected column must be grouped or aggregated.
  • WHERE filters rows before grouping; HAVING filters groups after, and can use aggregates.
  • Databases run FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT in that order.

Key terms

GROUP BY
A clause that splits rows into groups sharing the same value, for per-group summaries.
HAVING
A clause that filters groups after aggregation.

Check your understanding

Answer all 4 questions, then check your answers to see an explanation for each one.

  1. 1. How many rows does `SELECT category, COUNT(*) FROM products GROUP BY category;` return for our shop?

  2. 2. You want only categories whose average price is above 300. Where does that condition go?

  3. 3. Why can ORDER BY use an alias from SELECT, but WHERE cannot?

  4. 4. What is wrong with `SELECT category, name, COUNT(*) FROM products GROUP BY category;`?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.