Loading
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_name
GROUP BY column_name
HAVING condition;


Example: employees Table

idnamesalarydepartment
1Amit60000IT
2Neha75000HR
3Rahul50000IT
4Priya90000Finance
5Karan45000HR


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_salary
FROM employees
GROUP BY department
HAVING SUM(salary) > 100000;

HAVING filters departments after grouping.


Why WHERE Cannot be Used Here

This will cause an error

WHERE SUM(salary) > 100000

Reason
WHERE cannot work with aggregate functions.


Example - 2: Departments with More Than One Employee

SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING 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 employees
WHERE department = 'IT'
GROUP BY department
HAVING 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

WHEREHAVING
Filters rowsFilters groups
Used before GROUP ByUsed after GROUP By
Cannot use aggregatesWorks with aggregates
Faster for now filteringUsed 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