SQL HAVING Clause

Hi Guys,
This SQL article explain how to use the SQL HAVING clause with example and syntax. Mainly the SQL HAVING clause is used in combination with the GROUP BY clause to restrict the groups of returned rows to only those whose the condition is TRUE.

Syntax


SELECT exp1, exp2, ... expn,
aggregate_function (aggregate_exp)
FROM tables
[WHERE conditions]
GROUP BY exp1, exp2, ... expn
HAVING condition;




Description

  • exp1, exp2, … expn:Expressions that are not encapsulated within an aggregate function.
  • aggregate_function: Aggregate functions in HTML5 are: SUM, COUNT, MIN, MAX, or AVG functions.
  • aggregate_exp:This is the column or expression that the aggregate_function will be used on.



  • tables:The tables that you wish to retrieve records from.
  • WHERE conditions:Fetch the data from table based on conditions. These are the conditions for the records to be selected.
  • HAVING condition:This is a further condition applied only to the aggregated results to restrict the groups of returned rows.

SQL HAVING Clause Example

We use HAVING Clause in SQL with different SQL aggregate functions.

1)Example – Using SUM aggregate function

In here, the HAVING clause explain with SUM aggregate functions in SQL.


SELECT name, SUM (salary)
FROM employee_details
GROUP BY name
HAVING SUM (salary) > 35000




The output like this:

name salary
Pritty 55000
Prince 45000
Princy 70000

2)Example – Using COUNT aggregate function


SELECT dept, COUNT(*) AS " Total Number of employees"
FROM employee_details
WHERE salary > 35000
GROUP BY dept
HAVING COUNT(*) > 10;




If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.

Leave a Reply

Your email address will not be published. Required fields are marked *