Find a course

Module 3: Summarizing DataLesson 6 of 1114 min

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.

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):

genrenum_booksavg_price
Sci-Fi219.50
Fiction214.75
Tech238.50
Mystery112.99
Food124.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.

AVG(price) per genreBar chart with 5 categories: Sci-Fi: $19.5; Fiction: $14.75; Tech: $38.5; Mystery: $12.99; Food: $24.$0$10$20$30$40Average priceSci-FiFictionTechMysteryFood$19.5$14.75$38.5$12.99$24
Computed from the course's sample books table.
AVG(price) per genre
ItemAverage price
Sci-Fi$19.5
Fiction$14.75
Tech$38.5
Mystery$12.99
Food$24

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. 1. Filter

    WHERE removes rows that fail its condition. Only the surviving rows are grouped.

  2. 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. 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. 4. Filter groups

    HAVING drops entire groups whose aggregate values fail its condition.

  5. 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:

  1. WHERE removes Night Ferry (2017) and River Road (2016).
  2. 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).
  3. AVG computes 19.50, 15.50, 38.50 and 24.00.
  4. 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);
Real SQLite, running in your browser on a fresh copy of the database.
  • 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.

SUM(total) per customer_idBar chart with 4 categories: Customer 1: $69.99; Customer 2: $24; Customer 3: $42; Customer 4: $59.5.$0$20$40$60$80Total spentCustomer 1Customer 2Customer 3Customer 4$69.99$24$42$59.5
Result of SELECT customer_id, SUM(total) FROM orders GROUP BY customer_id on the sample orders table. Customer 5 has no orders, so no group exists for them.
SUM(total) per customer_id
ItemTotal spent
Customer 1$69.99
Customer 2$24
Customer 3$42
Customer 4$59.5

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:

  1. FROM: pick the table (and perform joins).
  2. WHERE: filter individual rows.
  3. GROUP BY: form groups.
  4. HAVING: filter groups.
  5. SELECT: compute the output columns, aggregates and aliases.
  6. ORDER BY: sort the results.
  7. 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 < 15 fails 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_price works.
  • 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.

Logical processing order of a queryProcess diagram: FROM / JOIN → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.FROM / JOINWHEREGROUP BYHAVINGSELECTORDER BYLIMIT
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);
Real SQLite, running in your browser on a fresh copy of the database.
  • 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.

  1. FROM
  2. ORDER BY
  3. GROUP BY
  4. LIMIT
  5. HAVING
  6. SELECT
  7. 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;