Filtering groups with HAVING
Stage 3: Aggregation · Lesson 12 of 17 · 5 min read · free, interactive
WHERE filters rows before they are grouped. HAVING filters groups after the aggregates are computed — so it can use COUNT, SUM and friends:
SELECT country, COUNT(*) AS players FROM players GROUP BY country HAVING COUNT(*) >= 2;
Both can appear in the same query. Here WHERE drops cheap items first, then HAVING keeps categories that still have items left:
SELECT category, COUNT(*) AS items FROM items WHERE price >= 5 GROUP BY category HAVING COUNT(*) >= 1;
Tip: The order of the clauses is fixed: SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY … LIMIT.
Practice
Each answer runs in your browser and is checked on hidden data.
- Write the query: Return each
countrythat has at least 2 players, with the count asplayers. Row order does not matter. - Find the bug: Return the categories whose average price is above 5:
categoryandavg_price(rounded to 2 decimals). Row order does not matter. - Fill in the blanks: Return the
winner_idof every player who won 2 or more matches, with the count aswins. Row order does not matter.
Previous: Groups with GROUP BY · Next: Counting distinct values · All lessons