How to use the HAVING clause
· Category: SQL & Databases
Short answer
HAVING filters groups after GROUP BY and aggregate functions have been applied, unlike WHERE which filters rows before aggregation.
Steps
- Filter groups by count:
SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5; - Filter by average:
SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 60000; - Combine
WHEREandHAVING:SELECT department, AVG(salary) FROM employees WHERE hire_date > '2024-01-01' GROUP BY department HAVING AVG(salary) > 50000; - Use multiple conditions:
HAVING COUNT(*) > 5 AND AVG(salary) > 50000 - Reference aggregate results by alias in some databases, or repeat the expression.
Tips
- Use
WHEREto reduce the row set before grouping for better performance. HAVINGcan reference selected aggregates and grouping columns.
Common issues
- Using
HAVINGwithoutGROUP BYtreats the entire result as one group. - Attempting to filter individual rows in
HAVINGis a logic error; useWHEREinstead.r