Loading
SQL HAVING Clause-tutorial

SQL HAVING Clause

  • The HAVING clause in SQL is used in conjunction with the GROUP BY clause to filter the results of a query based on a specified condition.

Syntax:

SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;
  
  • column1: The column(s) by which you are grouping the results.
  • aggregate_function(column2): An aggregate function (e.g., SUM, COUNT, AVG, etc.) applied to another column (column2).
  • condition: The condition that the aggregated results must satisfy.

Example:

 Employee table

Emp_ id

Emp _ name

working_ date

working_ hours

1

Ajeet

2015-01-24

12

2

Ayan

2015-01-24

10

3

Milan

2015-01-25

9

1

Ayan

2015-01-25

6

2

Ajeet

2015-01-25

4

 we use the SUM function with the HAVING Clause to return the emp_ name and sum of their working hours.

SELECT emp_ name, SUM(working_ hours) AS "Total working hours"  
FROM employees  
GROUP BY  emp_ name
HAVING SUM(working_ hours) > 5;

output:

emp_ name

Total working_ hours

Ajeet

16

Ayan

16

Milan

9