Loading Data Driven Insights
Preparing your learning content.
Preparing your learning content.
A beginner-friendly guide to the SQL HAVING clause, with SQL Server-friendly examples for filtering grouped query results after GROUP BY.
On this page
Jump to a lesson section
The HAVING clause is used to filter grouped results.
It is commonly used after GROUP BY, especially when you want to filter groups using aggregate values such as count, total, average, minimum value, or maximum value.
HAVING is written after GROUP BY because it filters the grouped result, not the original individual rows.
SELECT
column_name,
aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING aggregate_function(column_name) condition;
SELECT
department,
COUNT(*) AS total_employees
FROM Employees
GROUP BY department
HAVING COUNT(*) > 1;
We will group this Employees table by department, then use HAVING to filter the grouped result.
This query groups employees by department, counts the rows in each department, and then keeps only the departments with more than one employee.
SELECT
department,
COUNT(*) AS total_employees
FROM Employees
GROUP BY department
HAVING COUNT(*) > 1;
HR group is not returned because it has only one employee.WHERE and HAVING both filter data, but they are used at different stages of the query.
SELECT
department,
AVG(salary) AS average_salary
FROM Employees
GROUP BY department
HAVING AVG(salary) > 45000;
WHERE to filter rows before grouping.HAVING to filter groups after grouping.GROUP BY.Use WHERE for row-level filters and HAVING for aggregate/group filters.
SQL Roadmap Progress
Topic 22 of 111
20% complete
Next in SQL Roadmap
Continue with the next SQL topic in the recommended roadmap order.
Continue learning →