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.
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.
Learning SQL in order?
Use the roadmap to follow each SQL topic step by step, from relational database basics to advanced query techniques.
Back to SQL RoadmapRelated lessons
ALTER TABLE
A beginner-friendly guide to ALTER TABLE in SQL, including how to add, change, and remove columns from an existing table.
CREATE TABLE
A beginner-friendly guide to the SQL CREATE TABLE statement, including table planning, column names, data types, and a SQL Server-friendly example.
DELETE
A beginner-friendly guide to the SQL DELETE statement, with SQL Server-friendly examples for removing rows from a table safely.