FILTERING : HAVING Clause
Having Clause is used to Filter the Group.
SYNTAX:
SELECT group_by_expression / group_function
FROM table_name
[WHERE <filter_condition>]
GROUP BY column_name/expression
HAVING <group_filter_condition>
ORDER OF EXECUTION:
1- FROM
2- WHERE(if used) [ROW-BY-ROW]
3- GROUP BY(if used) [ROW-BY-ROW]
4- HAVING (if used ) [GROUP-BY-GROUP]
5- SELECT [GROUP-BY-GROUP]
NOTE:
1. Having clause is used to filter the groups by using it along with group by clause.
2. It executes after group by clause.
3. It executes group by group.
4. The select clause executes after having clause.
5. We can use multi-row functions in the having clause.
EXAMPLE
➢ WAQTD to find number of employees working in each
Dept if there are at least 3 employees in each dept .
SELECT DEPTNO , COUNT(*)FROM EMP
GROUP BY DEPTNO
HAVING COUNT(*)>=3;
Questions :
1. WAQTD the designations in which there are at lest 2 employees
Present .
SELECT JOB , COUNT(*)
FROM EMP
GROUP BY JOB
HAVING COUNT(*)>=2 ;
2. WAQTD the names that are repeated .
SELECT ENAME , COUNT(*)
FROM EMP
GROUP BY ENAME
HAVING COUNT(*) > 1 ;
3. WAQTD names that are repeated exactly twice .
SELECT ENAME , COUNT(*)
FROM EMP
GROUP BY ENAME
HAVING COUNT(*) = 2 ;
4. WAQTD the salary that is repeated .
SELECT SAL, COUNT(*)
FROM EMP
GROUP BY SAL
HAVING COUNT(*) > 1 ;
5. WAQTD number of employees working in each dept having
At least 2 emp's Character 'A' or 'S' in their names .
SELECT DEPTNO , COUNT(*)
FROM EMP
WHERE ENAME LIKE '%A%' OR ENAME LIKE '%S%'
GROUP BY DEPTNO
HAVING COUNT(*)>=2 ;
6. WAQTD job and total salary of each job , if the total salary
Of each job is greater than 3450 .
SELECT JOB , SUM( SAL )
FROM EMP
GROUP BY JOB
HAVING SUM( SAL ) > 3450 ;
7. WAQTD job and total salary of the employees if the employees
Are earning more than 1500.
SELECT JOB , SUM( SAL )
FROM EMP
WHERE SAL > 1500
GROUP BY JOB ;
New Section 1 Page 2
8. WAQTD Job wise maximum salary if the maximum salary
Of each job exceeds 2000 .
SELECT JOB , MAX( SAL )
FROM EMP
GROUP BY JOB
HAVING MAX( SAL ) > 2000 ;
9. WAQTD number of emp earning sal more than 1200 in each job
and the total sal needed to pay emp of each job must exceeds
3800.
SELECT JOB , COUNT(*) , SUM( SAL )
FROM EMP WHERE SAL > 1200
GROUP BY JOB
HAVING SUM( SAL ) > 3800 ;
New Section 1 Page 3