Definition, Use of Group by and Having Clause
Estimated study time: 12 minutes. Group your data, then filter the groups themselves.
GROUP BY and HAVING work together to summarize data by category and then filter those summaries — something a plain WHERE clause can't do on its own.
What GROUP BY Does
Groups rows that share the same value in one or more columns, so aggregate functions can be applied per group instead of across the whole table.
SELECT department, COUNT(*) AS total_employees FROM employees GROUP BY department;
What HAVING Does
HAVING filters groups after aggregation, unlike WHERE, which filters individual rows before grouping happens.
SELECT department, COUNT(*) AS total_employees FROM employees GROUP BY department HAVING COUNT(*) > 10;
Using WHERE and HAVING Together
SELECT department, AVG(salary) AS avg_salary FROM employees WHERE hire_date > '2020-01-01' GROUP BY department HAVING AVG(salary) > 60000;
Here, WHERE filters out employees hired before 2020 first, then GROUP BY groups the remaining rows, and finally HAVING keeps only departments whose average salary exceeds 60,000.
COUNT() inside a WHERE clause — that's exactly why HAVING exists.Common Mistakes
- Trying to filter on an aggregate using
WHEREinstead ofHAVING - Selecting a column that isn't in
GROUP BYor wrapped in an aggregate function - Forgetting that
HAVINGruns after grouping, so it can reference aggregate results directly