SQL HAVING Clause

SQL HAVING Clause

Having clause is used to filter data based on the group functions. This is similar to WHERE clause but is used with group functions. Group functions cannot be used in WHERE Clause but can be used in HAVING clause and thats why HAVING Clause was added to SQL.

HAVING Syntax

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition;

HAVING Example

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
-----------  -------------
Science        35000
Commerce       35000
Wrestling      30000

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 are executed and are grouped based on the GROUP BY clause.

Finally, the condition in the having clause is applied to the grouped rows and finally the output is displayed.

Prev - SQL GROUP BY Clause Next - SQL INSERT Statement

Comments