SQL HAVING
We already know that the WHERE clause is used to filter records. But there is a limitation. WHERE works on individual rows, not on groups.
Now think about questions like:
- Departments having more than 5 employees
- Cities where average salary is greater than 50,000
- Subjects where total marks exceed 300
These conditions are applied after grouping and aggregation, not before. This is where the HAVING clause becomes necessary.
What Is the HAVING Clause?
The HAVING clause is used to filter grouped results after the GROUP BY clause has been applied.
WHERE filters rows, HAVING filters groups.
When Do We Use HAVING?
HAVING is used when:
- GROUP BY is present
- Aggregate functions are involved
- Conditions are applied on aggregated values
Syntax
SELECT column_name, aggregate_function(column_name)FROM table_nameGROUP BY column_nameHAVING condition;Example: employees Table
| id | name | salary | department |
|---|---|---|---|
| 1 | Amit | 60000 | IT |
| 2 | Neha | 75000 | HR |
| 3 | Rahul | 50000 | IT |
| 4 | Priya | 90000 | Finance |
| 5 | Karan | 45000 | HR |
Example - 1: Departments with Total Salary Greater Than 1,00,000
Problem: Show only those departments whose total salary exceeds 100,000.
SELECT department, SUM(salary) AS total_salaryFROM employeesGROUP BY departmentHAVING SUM(salary) > 100000;HAVING filters departments after grouping.
Why WHERE Cannot be Used Here
This will cause an error
WHERE SUM(salary) > 100000Reason
WHERE cannot work with aggregate functions.
Example - 2: Departments with More Than One Employee
SELECT department, COUNT(*) AS employee_countFROM employeesGROUP BY departmentHAVING COUNT(*) > 1;Only departments having more than one employee are shown.
HAVING with WHERE
Execution Order
1. WHERE - filters rows
2. GROUP BY - groups rows
3. Aggregate functions - applied
4. HAVING - filters groups
5. ORDER BY - sorts final result
Example: IT Department with Average Salary Above 55,000
SELECT department, AVG(salary)FROM employeesWHERE department = 'IT'GROUP BY departmentHAVING AVG(salary) > 55000;WHERE filters rows first, HAVING filters grouped result.
Common Use Cases of HAVING
- Filtering aggregated data
- Report generation
- Analytical queries
- Dashboard metrics
Difference Between WHERE and HAVING
| WHERE | HAVING |
|---|---|
| Filters rows | Filters groups |
| Used before GROUP By | Used after GROUP By |
| Cannot use aggregates | Works with aggregates |
| Faster for now filtering | Used for grouped data |
Important Points About HAVING
- HAVING is mostly used with GROUP BY
- Aggregate functions are allowed in HAVING
- WHERE and HAVING can be used together
- HAVING without GROUP BY is allowed in some DBs but not recommended
Two Minute Drill
- HAVING filters grouped data
- Used after GROUP By
- Works with aggregate functions
- WHERE filters rows, HAVING filters groups
- Used in reports and analytics