WHERE filters rows before grouping; HAVING filters groups after aggregation. When your condition involves an aggregate ("programmes with more than 5 students"), you need HAVING.
Filtering groups
SELECT programme, COUNT(*) AS n, AVG(package) AS avg_pkgFROM studentsWHERE package > 0 -- filter ROWS before groupingGROUP BY programmeHAVING COUNT(*) >= 5 -- filter GROUPS after aggregatingORDER BY avg_pkg DESC;
Key takeaways
- 01WHERE filters rows before grouping; HAVING filters groups after aggregation.
- 02Use HAVING for conditions on aggregate values (e.g. COUNT(*) >= 5).
- 03Clause order: WHERE → GROUP BY → HAVING → ORDER BY.
- 04Prefer WHERE to cut rows early; use HAVING only on aggregated results.
