🔹 HAVING Clause in SQL

Definition:
The HAVING clause is used to filter grouped records created by GROUP BY. Unlike WHERE which filters rows **before** grouping, HAVING filters **after** the grouping is done. It's often used with aggregate functions like COUNT(), SUM(), AVG(), etc.
Syntax:
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;
Example:
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 3;
Sample employees Table:
idnamedepartment
1AliceHR
2BobIT
3CharlieIT
4DaisyHR
5EvaIT
6FrankHR
7GraceSales
8HenryHR
Output:
departmentemployee_count
HR4
Explanation:
The query groups employees by their department using GROUP BY. Then, using the HAVING COUNT(*) > 3 clause, it filters only those departments where the number of employees is greater than 3. In our table, only the HR department has 4 employees, so it's the only one shown in the output.
Usage Tips:
  • Use HAVING only with GROUP BY or aggregate functions.
  • Use WHERE to filter rows before grouping and HAVING to filter after.
Common Mistake:
Trying to use HAVING without GROUP BY or an aggregate function:

SELECT name FROM employees HAVING department = 'IT';
✅ Use WHERE for such row-level conditions.
📘 Note: HAVING is essential when filtering results based on aggregates like total salary, average age, or count of items.
➡️ Next: INNER JOIN