SQL Having Clause

In SQL, SQL Having clause is used to filter data based on the group functions. The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.

 

Group functions cannot be used in WHERE Clause but can be used in HAVING clause.

SQL Syntax :

SELECT aggregate_function(column_name)
FROM table_name
WHERE column_name
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;

 

SQL Having Clause with Example

Now we will see how can we use Having Clause to apply filters to aggregate functions.

Query –  Find the Departments where Department salary is greater than 15000$.

SQL> Select Sum(Salary), Department_id from Employees Group By Department_id Having Sum(Salary) >15000;

Having Clause in SQL

 

 

When WHERE, GROUP BY and HAVING clauses are used together in a SELECT statement, the WHERE clause is processed first, then the rows that are returned after the WHERE clause is executed are grouped based on the GROUP BY clause.

Finally, any conditions on the group functions in the HAVING clause are applied to the grouped rows before the final output is displayed.

Like –

If you want to select the department that has total salary paid for its employees more than 25000, the sql query would be like;

SELECT dept, SUM (salary)
FROM employee
GROUP BY dept
HAVING SUM (salary) > 25000

The output would be like:

dept salary
————- ————-
Electronics 55000
Aeronautics 35000
InfoTech 30000
0 Comment

Leave a Reply