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 (like SUM).
  • HAVING: Filters groups AFTER grouping. It is used specifically with aggregate functions.

πŸ’» Code example

sql Standard
SELECT 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 SELECT list that is NOT part of the GROUP BY clause (this is an error in most SQL engines, although MySQL allows it under some settings).
  • ORDER BY location: Placing ORDER BY before GROUP BY or HAVING (it must always come last).
  • NULLs in aggregates: Forgetting that aggregate functions (except COUNT(*)) ignore NULL values.