SQLMentor // glossary

HAVING

HAVING filters groups after GROUP BY has run, based on a condition that can reference aggregate functions. WHERE, by contrast, filters individual rows before grouping and cannot reference aggregates.

A condition that doesn't need an aggregate belongs in WHERE, not HAVING — filtering rows before grouping means the database has less work to do than grouping everything first and filtering afterward.

With no GROUP BY at all, HAVING is still legal — it treats the entire table as one group.

Example

SELECT department_id, COUNT(*) AS emp_count
FROM employees
GROUP BY department_id
HAVING COUNT(*) > 5;