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.
🎯 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
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
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status;Result: 3 rows
| status | orders |
|---|---|
| cancelled | 2 |
| delivered | 10 |
| shipped | 3 |
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:
SELECT category, COUNT(*) AS products, MIN(price) AS cheapest, MAX(price) AS dearest
FROM products
GROUP BY category;Result: 4 rows
| category | products | cheapest | dearest |
|---|---|---|---|
| Books | 2 | 350 | 450 |
| Electronics | 2 | 299 | 1200 |
| Home | 2 | 249 | 399 |
| Stationery | 2 | 90 | 120 |
Sorting groups
Sort by the aggregate's alias to rank the groups. A second sort column keeps ties in a predictable order:
SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country
ORDER BY customers DESC, country;Result: 7 rows
| country | customers |
|---|---|
| India | 4 |
| Australia | 1 |
| Canada | 1 |
| Ghana | 1 |
| Singapore | 1 |
| UAE | 1 |
| UK | 1 |
Filtering groups with HAVING
WHERE filters rows before grouping. HAVING filters groups after the aggregates are calculated, so it can use them:
SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country
HAVING COUNT(*) > 1;Result: 1 row
| country | customers |
|---|---|
| India | 4 |
You can use both in one query. Which customers bought at least 3 items, not counting cancelled orders?
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
| customer_id | items |
|---|---|
| 8 | 6 |
| 1 | 5 |
| 3 | 3 |
| 4 | 3 |
| Clause | Filters | Can use aggregates? | In this query |
|---|---|---|---|
WHERE | rows, before grouping | No | drops the 2 cancelled orders |
HAVING | groups, after grouping | Yes | drops 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:
| Step | Clause | Consequence |
|---|---|---|
| 1 | FROM | Start with the table's rows |
| 2 | WHERE | Runs before grouping, so it cannot use COUNT or SUM |
| 3 | GROUP BY | Rows become groups |
| 4 | HAVING | Can use aggregates, because groups now exist |
| 5 | SELECT | Aliases are created here... |
| 6 | ORDER BY | ...so ORDER BY can use an alias such as items |
| 7 | LIMIT | Cuts 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.
- Select
substr(order_date, 1, 7) AS monthandCOUNT(*) AS orders. - Group by
month. - Run it and check the counts add up to 15.
Show the solution
SELECT substr(order_date, 1, 7) AS month, COUNT(*) AS orders
FROM orders
GROUP BY month;Result: 2 rows
| month | orders |
|---|---|
| 2025-09 | 10 |
| 2025-10 | 5 |
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
SELECT product_id, COUNT(*) AS times_ordered
FROM orders
GROUP BY product_id
ORDER BY times_ordered DESC, product_id;Result: 7 rows
| product_id | times_ordered |
|---|---|
| 3 | 3 |
| 1 | 2 |
| 2 | 2 |
| 4 | 2 |
| 5 | 2 |
| 6 | 2 |
| 7 | 2 |
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 columnmakes one result row per different value, with aggregates calculated per group.- Every selected column must be grouped or aggregated.
WHEREfilters rows before grouping;HAVINGfilters 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. How many rows does `SELECT category, COUNT(*) FROM products GROUP BY category;` return for our shop?
2. You want only categories whose average price is above 300. Where does that condition go?
3. Why can ORDER BY use an alias from SELECT, but WHERE cannot?
4. What is wrong with `SELECT category, name, COUNT(*) FROM products GROUP BY category;`?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.