Having Clause
Having Clause
CONTENTS
• Introduction
• Syntax and Order of execution of having clause
• Why/When we are using having clause
• Difference between where and having clause
• Queries of Having clause
INTRODUCTION
• Syntax:
SELECT group_by_expression / group_function
FROM table_name
[WHERE <filter_condition>]
GROUP BY column_name/expression
HAVING <group_filter_condition
Order by column_name / group_function asc/desc;
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]
6. ORDER BY(if used) [ROW-BY-ROW]
WHY / WHEN WE ARE USING HAVING CLAUSE
• The SQL HAVING clause is similar to the WHERE clause; both are used to filter rows in
a table based on condition . However, the HAVING clause is used to filter grouped rows
instead of single rows. These rows are grouped together by the GROUP BY clause, so,
the HAVING clause must always be followed by the GROUP BY clause.
• Moreover, the HAVING clause can be used with aggregate functions such as COUNT(),
SUM(), AVG(), etc., whereas the WHERE clause cannot be used with them.
If suppose:
Write a query the total salary, average salary of all employees with average salary is greater then 60000 in
each department.
1. select sum(sal), avg(sal)
Don’t write this format Boz
from emp
where clause is not applicable
where avg(sal)>60000 to use Aggregation functions
group by dept-id;
2. select sum(sal),avg(sal)
from emp
group by dept-id
having avg(sal)>60000;
DIFFERENCE B/W WHERE AND HAVING CLAUSE
• Write a query the dep-id, total salary, average salary of all employees with average salary
is greater then 60000 in each department and order by dep-id in desc order.
select dep-id, sum(sal), avg(sal)
from emp
group by dep-id
having avg(sal)>60000
order by dep-id desc;