Mastering SQL Aggregations and Having Clauses Like a Pro
Learn COUNT, SUM, AVG, MIN, and MAX aggregations, how GROUP BY works under the hood, and the difference between WHERE and HAVING.
Data analysis relies heavily on summarizing datasets. SQL aggregation queries let you consolidate thousands of records into meaningful metrics. Grasping the logical order of query execution (FROM -> JOIN -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY) is essential.
The Difference Between WHERE and HAVING
One of the most frequent interview traps is using the HAVING clause when WHERE is appropriate, or vice versa:
- WHERE filters rows before aggregation occurs. It cannot reference aggregate functions like SUM() or AVG(). - HAVING filters the aggregated groups after GROUP BY evaluates. It operates strictly on group summary values.
-- Retrieve departments with average salary > 100k SELECT DeptID, AVG(Salary) as AvgSalary FROM Employee WHERE JobTitle != 'CEO' -- Filter individual rows GROUP BY DeptID HAVING AVG(Salary) > 100000; -- Filter grouped rows
Quick Concept Quiz
Which SQL clause is evaluated BEFORE the GROUP BY clause?
Ready to test your execution tracing skills?
Hop directly into the SQL interactive playground to start coding, grading queries, and logging XP metrics to your workspace profile.