Skip to content
CodeItRaw
SQL: Grouping

Lesson 2/2

Once the groups exist you may want to filter them as well: "the genres whose average price is above 80". That condition cannot be asked of a single row, because the average only exists once the group is built. WHERE filters rows; `HAVING` filters groups.

SELECT genre, AVG(price) AS average
FROM books
WHERE year >= 2000
GROUP BY genre
HAVING COUNT(*) >= 3
ORDER BY average DESC;
It runs in this order: WHERE drops the books from before 2000, GROUP BY sorts the rest into genres, HAVING drops the genres with fewer than three books, ORDER BY sorts the result. WHERE runs before the grouping, HAVING after.

Totalling by a period of time is the same pattern: group by the month column, add the amount up with SUM, sort by month. A large share of all reports is those three lines.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Average salary

    SQL query

  2. 02

    Busy departments

    SQL query

  3. 03

    Monthly sales

    SQL query

If you would rather not wait for the order, every problem is open without locks: Problem list