🧮 HAVING Clause in SQL

Last Updated: January 2026


The HAVING clause is used to filter grouped data

In short:

  • WHERE → filters rows
  • HAVING → filters groups

🧠 Why HAVING Exists ?

WHERE cannot be used with aggregate results like COUNT(), SUM(), AVG().# Example ❌ (Invalid):

SELECT department, COUNT(*)
FROM employees
WHERE COUNT(*) > 5
GROUP BY department;

This fails because:

  • WHERE runs before grouping
  • Aggregate values do not exist yet

Hinglish Tip 🗣: Jab condition group ke result par lagani ho → HAVING use hota hai, WHERE nahi.

Basic Syntax

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

🔄 SQL Execution Order (With HAVING)

Understanding this removes 90% confusion:

  1. FROM
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. SELECT
  6. ORDER BY
  7. LIMIT

👉 That’s why HAVING can see aggregate values.


Example 1: Filter Groups Using COUNT

SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;

Meaning:

  • Group by department
  • Keep only departments with more than 5 employees

Example 2: HAVING with SUM

SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING SUM(salary) >= 100000;

✔ Filters departments based on total salary


Example 3: WHERE + HAVING Together

SELECT department, AVG(salary)
FROM employees
WHERE status = 'Active'
GROUP BY department
HAVING AVG(salary) > 50000;

Logic:

  • WHERE → filters rows (Active employees)
  • HAVING → filters groups (avg salary condition)