SQL Keyword - HAVING

SQL Keyword - HAVING

The Having keyword is used to apply a filter to the group by clause result.

The where clause is not applicable in the aggregate result, so the having clause is introduced.

The Having clause is used after the group by clause.

The Having clause is used with select queries.

Syntax

SELECT AGGREGATE_FUNCTION(<COLUMN_NAME>) FROM <TABLE_NAME> GROUP BY <COLUMN_NAME>
HAVING AGGREGATE_FUNCTION(<COLUMN_NAME>) <OPERATOR> <VALUE>

Example 1

SELECT Emp_Dept,COUNT(Emp_Dept) 'No Of Employee' FROM Employee GROUP BY Emp_Dept HAVING COUNT(Emp_Dept) > 5

Example 2

SELECT County, State, MIN(P_Age) As Min_Age,MAX(P_Age) As Max_Age FROM Persons
GROUP BY County, State HAVING  MIN(P_Age) >= 18 And  MAX(P_Age) <= 50

Example 3

SELECT Emp_Dept ,COUNT(Emp_Dept) 'No Of Employee',SUM(Emp_Salary) 'Total Salary' FROM Employee 
GROUP BY Emp_Dept HAVING  COUNT(Emp_Dept) >= 2 AND SUM(Emp_Salary) < 50000

Summary

The Having keyword is used to apply a filter to the group by clause result.