ADVERTISEMENT

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

ClauseWhen It WorksFilters On
WHEREBefore groupingIndividual rows
HAVINGAfter grouping (aggregation)Groups (aggregated results)

🧠 Quick Recap

Key PointExplanation
Use HAVING to filter grouped data after GROUP BYFilters 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 groupingApplies to individual rows, not grouped results
Use WHERE for row-level filtering and HAVING for group-level filteringBoth can be combined for precise filtering

✅ Use HAVING when filtering on aggregated data

ADVERTISEMENT