GROUP BY and HAVING: Summaries per Group
Calculate aggregates per group with GROUP BY, filter groups with HAVING, and learn the logical order in which SQL actually processes a query.
Welcome back!
Step 1 of 16Learn
One summary row per group
"What's the average price?" has one answer. "What's the average price per genre?" has one answer per genre. GROUP BY splits rows into groups that share a value, then calculates aggregates separately for each group.
SELECT genre, COUNT(*) AS num_books, AVG(price) AS avg_price
FROM books
GROUP BY genre;Result (in no guaranteed order):
| genre | num_books | avg_price |
|---|---|---|
| Sci-Fi | 2 | 19.50 |
| Fiction | 2 | 14.75 |
| Tech | 2 | 38.50 |
| Mystery | 1 | 12.99 |
| Food | 1 | 24.00 |
Think of it as sorting the books into piles by genre, then computing the count and average of each pile.
The rule from the last lesson now makes sense: every column in SELECT must be either in GROUP BY or inside an aggregate. Genre is fine because it's the same for every row in a pile. Title is not, because each pile can contain several titles.
You can group by more than one column, creating a group for each unique combination: GROUP BY author, genre. And you can sort the summary:
SELECT author, COUNT(*) AS books, SUM(stock) AS total_stock
FROM books
GROUP BY author
ORDER BY total_stock DESC;Results: Leo Park (2 books, 25 + 0 = 25 in stock), Mara Quinn (2 books, 21), Jo Banks (1 book, 18), Ana Ruiz (2 books, 7, since the NULL is ignored) and Sam Odell (1 book, 3).
GROUP BY is SQL's version of a spreadsheet pivot table, and it's arguably the single most useful clause for analysis.
Step 2 of 16Practice · Chart
AVG(price) per genre
This is the result of SELECT genre, AVG(price) FROM books GROUP BY genre; drawn as bars: one bar per group.
Which genre has the lowest average price?
Tap the bar that answers the question, then press Check.
Step 3 of 16Practice · Work it out
Using the books table, how many rows does this query return? SELECT author, COUNT(*) FROM books GROUP BY author;
Step 4 of 16Tap to reveal
What GROUP BY does behind the scenes
1. Filter
WHERE removes rows that fail its condition. Only the surviving rows are grouped.
2. Sort into piles
The database collects rows with identical values in the GROUP BY columns into one group. With GROUP BY genre on the books table, that makes five piles.
3. Compute aggregates
Each aggregate, such as COUNT(*) or AVG(price), is calculated separately within each pile, so each pile is reduced to a single row.
4. Filter groups
HAVING drops entire groups whose aggregate values fail its condition.
5. Present
SELECT outputs one row per remaining group, and ORDER BY sorts those summary rows. NULL values in a grouping column form their own group.
Step 5 of 16Learn
Filtering groups with HAVING
Suppose you want only the genres with at least 2 books. You can't use WHERE, because WHERE filters individual rows before grouping, and at that point there is no count yet. HAVING filters groups after aggregation:
SELECT genre, COUNT(*) AS num_books
FROM books
GROUP BY genre
HAVING COUNT(*) >= 2;This returns Sci-Fi, Fiction and Tech, each with 2 books.
WHERE and HAVING can work together. Which genres have an average price above $15, counting only books published since 2018?
SELECT genre, AVG(price) AS avg_price
FROM books
WHERE year >= 2018
GROUP BY genre
HAVING AVG(price) > 15;Step by step:
- WHERE removes Night Ferry (2017) and River Road (2016).
- GROUP BY makes piles from the 6 remaining books: Sci-Fi (18.00, 21.00), Fiction (15.50), Tech (42.00, 35.00), Food (24.00).
- AVG computes 19.50, 15.50, 38.50 and 24.00.
- HAVING keeps groups above 15: all four.
A guideline for choosing: if a condition is about individual rows, put it in WHERE; if it's about an aggregate, put it in HAVING. Filtering rows early with WHERE is also more efficient, because fewer rows need grouping.
Using the orders table, here's a business question: which customers have placed more than one order?
SELECT customer_id, COUNT(*) AS orders, SUM(total) AS spent
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 1;Only customer 1 qualifies, with 3 orders totaling 36.00 + 12.99 + 21.00 = 69.99.
Step 6 of 16Practice · Code challenge · SQL
Code challenge · SQL
For each genre, return the genre, the number of books in it, and the average price rounded to 2 decimals (use ROUND(…, 2)).
Columns: genre, count, average.
The database for this exercise (tables and rows)
CREATE TABLE books (
book_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
genre TEXT,
price REAL,
year INTEGER,
stock INTEGER
);
INSERT INTO books VALUES
(1, 'The Silent Orbit', 'Mara Quinn', 'Sci-Fi', 18.00, 2019, 12),
(2, 'Gardens of Salt', 'Leo Park', 'Fiction', 15.50, 2021, 0),
(3, 'Data in Practice', 'Ana Ruiz', 'Tech', 42.00, 2022, 7),
(4, 'Night Ferry', 'Leo Park', 'Mystery', 12.99, 2017, 25),
(5, 'Learning to Cook', 'Sam Odell', 'Food', 24.00, 2020, 3),
(6, 'The Last Signal', 'Mara Quinn', 'Sci-Fi', 21.00, 2023, 9),
(7, 'Quiet Numbers', 'Ana Ruiz', 'Tech', 35.00, 2018, NULL),
(8, 'River Road', 'Jo Banks', 'Fiction', 14.00, 2016, 18);- Result matches the expected table
Step 7 of 16Note
Step 8 of 16Practice · Work it out
Using the orders table above, what total does this query return for customer 1? SELECT customer_id, SUM(total) FROM orders GROUP BY customer_id;
Step 9 of 16Practice · Chart
SUM(total) per customer_id
Which customer would remain if you added HAVING SUM(total) > 60?
Tap the bar that answers the question, then press Check.
Step 10 of 16Learn
The order SQL really runs in
You write a query in this order:
SELECT → FROM → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT
But the database processes it, logically, in a different order:
- FROM: pick the table (and perform joins).
- WHERE: filter individual rows.
- GROUP BY: form groups.
- HAVING: filter groups.
- SELECT: compute the output columns, aggregates and aliases.
- ORDER BY: sort the results.
- LIMIT: keep only the first rows.
This logical order explains several rules that otherwise seem arbitrary:
- Why aggregates can't go in WHERE. WHERE runs at step 2, before groups exist at step 3.
- Why a SELECT alias usually can't be used in WHERE.
SELECT price * 0.9 AS sale_price ... WHERE sale_price < 15fails in most databases, because aliases are created at step 5, after WHERE. Repeat the expression instead:WHERE price * 0.9 < 15. - Why ORDER BY can use aliases. It runs at step 6, after SELECT has named the columns:
ORDER BY sale_priceworks. - Why LIMIT comes last. You sort the whole result, then take the top rows.
Some databases relax these rules, for example allowing aliases in GROUP BY or HAVING, but writing queries that follow the logical order works everywhere.
When a complex query misbehaves, walk through it in this order and picture the intermediate table after each step. It's the most reliable debugging technique for SQL.
Step 11 of 16Practice · Diagram
Logical processing order of a query
Written order starts with SELECT; processing order does not. Tap a step.
A SELECT alias such as book_count can't be used in WHERE in standard SQL. Tap the first step where it can be used.
Tap the shape that answers the question, then press Check.
- FROM / JOIN
Assemble the rows to work with.
- WHERE
Drop individual rows. No groups or aggregates exist yet.
- GROUP BY
Bundle remaining rows into groups.
- HAVING
Drop whole groups, using aggregates like COUNT(*).
- SELECT
Compute output columns and aliases.
- ORDER BY
Sort the result; aliases from SELECT can be used here.
- LIMIT
Keep the first n rows.
Step 12 of 16Practice · Code challenge · SQL
Code challenge · SQL
Return each author who has more than one book, with the number of books they wrote.
The starter counts books for every author. Keep only the groups with a count above 1.
The database for this exercise (tables and rows)
CREATE TABLE books (
book_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
genre TEXT,
price REAL,
year INTEGER,
stock INTEGER
);
INSERT INTO books VALUES
(1, 'The Silent Orbit', 'Mara Quinn', 'Sci-Fi', 18.00, 2019, 12),
(2, 'Gardens of Salt', 'Leo Park', 'Fiction', 15.50, 2021, 0),
(3, 'Data in Practice', 'Ana Ruiz', 'Tech', 42.00, 2022, 7),
(4, 'Night Ferry', 'Leo Park', 'Mystery', 12.99, 2017, 25),
(5, 'Learning to Cook', 'Sam Odell', 'Food', 24.00, 2020, 3),
(6, 'The Last Signal', 'Mara Quinn', 'Sci-Fi', 21.00, 2023, 9),
(7, 'Quiet Numbers', 'Ana Ruiz', 'Tech', 35.00, 2018, NULL),
(8, 'River Road', 'Jo Banks', 'Fiction', 14.00, 2016, 18);- Result matches the expected table
Step 13 of 16Practice · Put in order
Put these clauses in the logical order the database processes them.
Drag the items, or use the arrow buttons, to put them in order.
- FROM
- ORDER BY
- GROUP BY
- LIMIT
- HAVING
- SELECT
- WHERE
Step 14 of 16Practice · Spot the mistake
This query should list genres whose books average more than $20, considering only books with known stock. Which lines contain errors? Click them.
Step 15 of 16Practice · Sort into groups
Should each condition go in WHERE or in HAVING?
Tap an item, then tap its group (or drag it there).
Step 16 of 16Practice · Choose one
Using the books table, what does this query return? SELECT genre FROM books GROUP BY genre HAVING AVG(price) > 20;
Lesson complete!