Database Management System (DBMS) / SQL(STRUCTURED QUERY LANGUAGE)

HAVING keyword

The HAVING clause is used to filter grouped results created by the GROUP BY clause.

It’s like WHERE, but works after aggregation (e.g., COUNT(), SUM()).


⚠️ Why Not Use WHERE?

🔹 WHERE filters rows before grouping

🔹 HAVING filters groups after aggregation


📌 Syntax

SELECT <column_name> AS <alias_name>
FROM <table_name>
GROUP BY <column_name>
HAVING <condition>;

➕ Example with SUM()

CREATE TABLE employees (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    department VARCHAR(50) NOT NULL,
    salary INT NOT NULL
);

-- Insert sample data
INSERT INTO employees (name, department, salary) VALUES
('Alice', 'Engineering', 120000),
('Bob', 'Engineering', 150000),
('Carol', 'Engineering', 180000),
('David', 'Marketing', 90000),
('Eve', 'Marketing', 85000),
('Frank', 'Sales', 100000),
('Grace', 'Sales', 110000),
('Heidi', 'Sales', 95000),
('Ivan', 'HR', 60000),
('Judy', 'HR', 55000);

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

✔️ Shows departments with total salary above ₹5 lakh


🚫 Invalid Example (Can’t Use Aggregates in WHERE)

❌ This won’t work:

SELECT grade, COUNT(*)
FROM students
WHERE COUNT(*) > 3
GROUP BY grade;

🛑 COUNT() cannot be used inside WHERE


📋 Summary

Clause

Works On

Used For

WHERE

Individual rows

Filter before grouping

HAVING

Groups

Filter after grouping

COUNT()/SUM()/AVG()

Aggregate functions

Must use in HAVING to filter groups