Having Clause
Having Clause
SYNTAX:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
EXAMPLES:
Student_details table, which helps to analyze the HAVING clause with the COUNT
aggregate function:
1 Rithik 91 20
2 Kapil 60 19
3 Arun 82 17
4 Ram 92 18
5 Anuj 50 20
6 Suman 88 18
7 Sheetal 57 19
8 Anuj 64 20
we want to count the number of students from the above table according to their age. For
this, we have to write the following query:
SELECT COUNT(Roll_No), Age FROM Student_details GROUP BY Age ;
The above query will show the following output:
Count(Roll_No) Age
3 20
2 19
1 17
2 18
suppose that we want to show the age of those students whose roll number is more than
and equals 2. For this case, we have to type the following query with the HAVING clause in
SELECT COUNT(Roll_No), Age FROM Student_details GROUP BY Age HAVING COU
NT(Roll_No) >= 2 ;
Count(Roll_No) Age
3 20
2 19
2 18
Example 2: Employee_Dept table, which helps to analyze the HAVING clause with
AVG aggregate function:
SELECT AVG(Emp_Salary), Emp_Dept FROM Employee_Dept GROUP BY Emp_Dept;
AVG(Emp_Salary) Emp_Dept
7000 Finance
4500 HR
6500 Coding
10000 Marketing
suppose that we want to show those departments whose average salary is more than
and equals 6500. For this case, with the HAVING clause in SQL:
SELECT AVG(Emp_Salary), Emp_Dept FROM Employee_Dept GROUP BY Emp_Dept H
AVING AVG(Emp_Salary) > 6500 ;
The above SQL query will show the following table in the output:
AVG(Emp_Salary) Emp_Dept
7000 Finance
6500 Coding
10000 Marketing