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.

Previous: Groups with GROUP BY · Next: Counting distinct values · All lessons