Skip to content

SQL HAVING Clause

Syntax

The HAVING clause in SQL is used to filter groups of records based on aggregate function results. It is used in conjunction with the GROUP BY clause.

-- Use HAVING to filter grouped results
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING aggregate_function(column2) condition;

Example

-- Retrieve departments with more than 1 employee
SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING COUNT(*) > 1;
/* Output:
| department | COUNT(*) |
|-------------|----------|
| Sales | 2 |
*/
-- Retrieve departments with an average salary above 50,000
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
/* Output:
| department | AVG(salary) |
|-------------|-------------|
| HR | 60000 |
*/