SQL Server HAVING Clause Example
The HAVING clause is used to filter grouped data after using GROUP BY.
Syntax
Example: Find Departments Having Total Salary Greater Than 100000
Employee Table
| EmpID | EmpName | Department | Salary |
|---|
| 1 | Amit | HR | 25000 |
| 2 | Ravi | IT | 40000 |
| 3 | Neha | IT | 35000 |
| 4 | Priya | HR | 30000 |
| 5 | Karan | Sales | 45000 |
| 6 | Simran | Sales | 60000 |
SQL Query
Result
| Department | TotalSalary |
|---|
| Sales | 105000 |
Explanation
-
GROUP BY Department → Groups employees department-wise.
-
SUM(Salary) → Calculates total salary of each department.
-
HAVING SUM(Salary) > 100000 → Displays only departments whose total salary is greater than 100000.
Difference Between WHERE and HAVING
| WHERE | HAVING |
|---|
| Filters rows before grouping | Filters groups after grouping |
| Cannot use aggregate functions directly | Can use aggregate functions |
| Used before GROUP BY | Used after GROUP BY |
Another Simple Example
Count Employees in Each Department
Result
| Department | TotalEmployee |
|---|
| HR | 2 |
| IT | 2 |
| Sales | 2 |
Comments
Post a Comment