Core Module
12 min forge
Aggregation: GROUP BY & HAVING
How to summarize data and filter grouped results.
Aggregation: GROUP BY & HAVING
π What is it
Aggregation functions perform a calculation on a set of values and return a single value. GROUP BY is used to arrange identical data into groups.
ποΈ Core Functions
COUNT(): Returns the number of rows.SUM(): Returns the total sum of a numeric column.AVG(): Returns the average value.MIN()/MAX(): Returns the smallest/largest value.
β‘ HAVING vs WHERE
This is the most common aggregation question:
WHERE: Filters rows BEFORE grouping. It cannot be used with aggregate functions (likeSUM).HAVING: Filters groups AFTER grouping. It is used specifically with aggregate functions.
π» Code example
sql StandardSELECT Department, COUNT(*) as EmployeeCount, AVG(Salary) as AvgSalary FROM Employees WHERE Status = 'Active' -- Filter rows first GROUP BY Department HAVING AVG(Salary) > 50000; -- Filter groups after
β Common mistakes
- Non-aggregated columns: Including a column in the
SELECTlist that is NOT part of theGROUP BYclause (this is an error in most SQL engines, although MySQL allows it under some settings). - ORDER BY location: Placing
ORDER BYbeforeGROUP BYorHAVING(it must always come last). - NULLs in aggregates: Forgetting that aggregate functions (except
COUNT(*)) ignoreNULLvalues.