softwaretips4u Tips that Transform
← Back to Homepage ← Back to Articles

GROUP BY & HAVING Clause in SQL

The GROUP BY and HAVING clauses are used to group rows based on column values and filter those groups after aggregation. They are essential for summary reports and analytical queries.

🔹 GROUP BY

SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;

👉 Shows how many employees are in each department.

🔹 HAVING

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

👉 Shows only departments with more than 5 employees.

🔹 Key Differences (WHERE vs HAVING)

Feature WHERE HAVING
Filters rows Before grouping After grouping
Works with Individual rows Aggregate/grouped results
Example WHERE salary > 50000 HAVING AVG(salary) > 60000
← Back to Articles | 🏠 Back to Homepage