PostgreSQL HAVING
The HAVING clause is similar to WHERE but applies to aggregated data grouped by GROUP BY. It filters groups based on aggregate function results.
Key Topics
1. Basic Syntax
Use HAVING after GROUP BY:
SELECT department, COUNT(*) AS dept_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
This returns only departments with more than 10 employees.
2. Example Usage
SELECT department, AVG(salary) as avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
This filters out departments whose average salary is 50,000 or less.
Best Practices
- Use
HAVINGto filter groups afterGROUP BYis applied. - Only reference aggregate functions or grouped columns in
HAVING.
Key Takeaways
HAVINGis used in conjunction withGROUP BYto filter aggregated data.- It functions similarly to
WHEREbut for grouped results.