Having Clause Aggregate Filter
Filter grouped results with HAVING after aggregation for group-level conditions.
Code
SELECT
department,
COUNT(*) AS employee_count,
AVG(salary) AS avg_salary,
MAX(salary) AS max_salary
FROM employees
WHERE status = 'active'
GROUP BY department
HAVING COUNT(*) > 5 AND AVG(salary) > 50000
ORDER BY avg_salary DESC;What the code does
The statement is SELECT, touching employees.
Concretely, the SQL combines: a WHERE clause that keeps only the rows a statement is meant to touch; COUNT, AVG, MAX aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.
Applying it
Run the statement against the employees table.
Statements that matter
SELECT
department,
COUNT(*) AS employee_count,
AVG(salary) AS avg_salary,
MAX(salary) AS max_salary
FROM employees
WHERE status = 'active'
GROUP BY department
HAVING COUNT(*) > 5 AND AVG(salary) > 50000
ORDER BY avg_salary DESC;
Interactive Tools for This Topic
FAQ
- Name the tables involved in this file.
- `employees`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.