SQL HAVING
HAVING
lets you filter grouped results after using GROUP BY
. Think of it as a WHERE
for aggregated data.
🔹 Basic Syntax
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition_on_aggregate;
🔹 Example: Departments with More Than 5 Employees
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
Only departments with more than 5 employees are shown.
🔹 Using Multiple Conditions
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 60000 AND COUNT(*) > 3;
🔹 Difference Between WHERE and HAVING
Clause | When It Works | Filters On |
---|---|---|
WHERE | Before grouping | Individual rows |
HAVING | After grouping (aggregation) | Groups (aggregated results) |
🧠 Quick Recap
Key Point | Explanation |
---|---|
Use HAVING to filter grouped data after GROUP BY | Filters groups based on aggregate conditions |
Conditions usually involve aggregate functions like COUNT() , AVG() , SUM() , etc. | Aggregate functions are required in HAVING conditions |
WHERE filters rows before grouping | Applies to individual rows, not grouped results |
Use WHERE for row-level filtering and HAVING for group-level filtering | Both can be combined for precise filtering |
✅ Use HAVING
when filtering on aggregated data