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 resultsSELECT column1, aggregate_function(column2)FROM table_nameGROUP BY column1HAVING aggregate_function(column2) condition;Example
-- Retrieve departments with more than 1 employeeSELECT department, COUNT(*)FROM employeesGROUP BY departmentHAVING COUNT(*) > 1;/* Output:| department | COUNT(*) ||-------------|----------|| Sales | 2 |*/
-- Retrieve departments with an average salary above 50,000SELECT department, AVG(salary)FROM employeesGROUP BY departmentHAVING AVG(salary) > 50000;/* Output:| department | AVG(salary) ||-------------|-------------|| HR | 60000 |*/