HAVING — Filter Groups After Grouping

The HAVING clause allows you to filter the groups created by GROUP BY.
It works like WHERE, but is used after grouping the data.

Use HAVING when you want to include or exclude entire groups based on aggregate values.

Syntax

SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;

Example 1: Departments with More Than 2 Employees

SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 2;

This returns only the departments that have more than 2 employees.

Example 2: Departments with Average Age Under 30

SELECT department, AVG(age)
FROM employees
GROUP BY department
HAVING AVG(age) < 30;

This returns departments where the average age of employees is less than 30.

Note: We will learn about the AVG function in coming chapters, but hope this gives you an idea on how we can use HAVING.


Tip

  • Use WHERE to filter rows before grouping.
  • Use HAVING to filter groups after grouping.

The HAVING clause gives you fine control over which groups you want to include in your final result!