SQL HAVING Clause
HAVING clause filters results after applying aggregate functions. Unlike WHERE, which filters individual rows, HAVING works with aggregated results.
Its main features include:
- Filters results based on aggregate functions.
- Supports Boolean conditions (AND, OR).
- Applied after aggregate functions in the query.
- Useful for summary-level or aggregated filtering.
Syntax:
SELECT AGGREGATE_FUNCTION(column_name)
FROM table_name
HAVING condition;
Examples of HAVING Clause
First, we create the Employee table and insert sample data to demonstrate the HAVING clause.
Query:
CREATE TABLE Employee (
EmployeeId int,
Name varchar(50),
Gender varchar(10),
Salary int,
Department varchar(20),
Experience int );
INSERT INTO Employee (EmployeeId, Name, Gender, Salary, Department, Experience)
VALUES (1, 'Emily Johnson', 'Female', 45000, 'IT', 2),
(2, 'Michael Smith', 'Male', 65000, 'Sales', 5),
(3, 'Olivia Brown', 'Female', 55000, 'Marketing', 4),
(4, 'James Davis', 'Male', 75000, 'Finance', 7),
(5, 'Sophia Wilson', 'Female', 50000, 'IT', 3);
SELECT * FROM Employee;
Output
| EmployeeId | Name | Gender | Salary | Department | Experience |
|---|---|---|---|---|---|
| 1 | Emily Johnson | Female | 45000 | IT | 2 |
| 2 | Michael Smith | Male | 65000 | Sales | 5 |
| 3 | Olivia Brown | Female | 55000 | Marketing | 4 |
| 4 | James Davis | Male | 75000 | Finance | 7 |
| 5 | Sophia Wilson | Female | 50000 | IT | 3 |
Example 1: Filter Total Salary
In this Example we calculate the total salary of all employees and display it only if it meets the specified condition.
Query:
SELECT SUM(Salary) AS Total_Salary
FROM Employee
HAVING SUM(Salary) >= 250000;
Output
| Total_Salary |
|---|
| 290000 |
Example 2: Filter Average Salary
In this example, we calculate the average salary of all employees and display it only if the average exceeds 55,000.
Query:
SELECT AVG(Salary) AS Average_Salary
FROM Employee
HAVING AVG(Salary) > 55000;
Output
| Average_Salary |
|---|
| 58000 |
Example 3: Filter Maximum Salary
In this example, we find the highest salary among employees and display it only if it exceeds 70,000.
Query:
SELECT MAX(Salary) AS Max_Salary
FROM Employee
HAVING MAX(Salary) > 70000;
Output
| Max_Salary |
|---|
| 75000 |
Example 4: Filter Minimum Experience
In this example, we find the least experienced employee and display it only if their experience is less than 3 years.
Query:
SELECT MIN(Experience) AS Min_Experience
FROM Employee
HAVING MIN(Experience) < 3;
Output
| Min_Experience |
|---|
| 2 |
Example 5: Multiple Conditions
In this example, we calculate both the total and average salary of employees and display the results only if the total salary is at least 250,000 and the average salary exceeds 55,000.
Query:
SELECT SUM(Salary) AS Total_Salary, AVG(Salary) AS Average_Salary
FROM Employee
HAVING SUM(Salary) >= 250000 AND AVG(Salary) > 55000;
Output
| Total_Salary | Average_Salary |
|---|---|
| 290000 | 58000 |