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
HAVING
to filter groups afterGROUP BY
is applied. - Only reference aggregate functions or grouped columns in
HAVING
.
Key Takeaways
HAVING
is used in conjunction withGROUP BY
to filter aggregated data.- It functions similarly to
WHERE
but for grouped results.