Filtering Groups with HAVING

Which genres have at least 3 games? WHERE filters rows, so you might try this:

SELECT genre, COUNT(*) AS game_count
FROM games
WHERE COUNT(*) >= 3
GROUP BY genre;
Error on line 1: misuse of aggregate: COUNT()

The database complains that COUNT is somewhere it doesn't belong. WHERE checks the rows one by one before they're grouped, and at that point, there's nothing to count yet. To filter groups, SQL has HAVING. It comes right after GROUP BY, and its condition is checked for each group once the aggregate functions are computed:

SELECT genre, COUNT(*) AS game_count
FROM games
GROUP BY genre
HAVING COUNT(*) >= 3
ORDER BY genre;
genregame_count
Action4
Adventure3
Strategy3

The groups that don't meet the condition are left out of the result. In HAVING, you can use everything you know from WHERE: comparisons, AND, OR, NOT, BETWEEN… and aggregate functions, even ones that aren't in SELECT. These are the genres whose games cost $25 or less on average:

SELECT genre
FROM games
GROUP BY genre
HAVING AVG(price) <= 25
ORDER BY genre;
genre
Adventure
Puzzle
Racing
Simulation

A query's parts are written in this order: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.

Typical mistake: WHERE instead of HAVING, as in the first query. Whenever a condition has an aggregate function in it, it belongs in HAVING.

Instructions

Show the customers who have placed at least 3 orders: customer_id and the number of their orders in a column order_count, sorted by customer_id:

customer_idorder_count
14
23
34
43
63

Below it, show the orders worth more than $60: order_id and the sum of quantity * price in a column order_total, from the most expensive, and the orders with the same total by order_id:

order_idorder_total
1185
1475
565
1065
2565

And the games that have at least 2 reviews and at least 4 stars on average: game_id, the number of reviews in a column review_count and the average stars rounded to 2 decimal places in a column average_stars, sorted by game_id:

game_idreview_countaverage_stars
144.25
324.5
624.0
724.5
1024.5
1524.5

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

8/10