SQL SERVER HAVING CLAUSE QUERY

SQL Server HAVING Clause Example

The HAVING clause is used to filter grouped data after using GROUP BY.

Syntax

SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;

Example: Find Departments Having Total Salary Greater Than 100000

Employee Table

EmpIDEmpNameDepartmentSalary
1AmitHR25000
2RaviIT40000
3NehaIT35000
4PriyaHR30000
5KaranSales45000
6SimranSales60000

SQL Query

SELECT Department, SUM(Salary) AS TotalSalary
FROM Employee
GROUP BY Department
HAVING SUM(Salary) > 100000;

Result

DepartmentTotalSalary
Sales105000

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

WHEREHAVING
Filters rows before groupingFilters groups after grouping
Cannot use aggregate functions directlyCan use aggregate functions
Used before GROUP BYUsed after GROUP BY

Another Simple Example

Count Employees in Each Department

SELECT Department, COUNT(*) AS TotalEmployee
FROM Employee
GROUP BY Department
HAVING COUNT(*) >= 2;

Result

DepartmentTotalEmployee
HR2
IT2
Sales2

Comments

Popular posts from this blog

STORE PROCEDURE BASIC PROGRAMMING - PART 1

Python Introduction