HAVING & aggregate conditions
Filter a group, not a row
Lesson 8 of 20 · 9 min · Module 3: See patterns in data
A report can first combine individual records into groups, then keep only groups meeting an aggregate condition.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Distinguish row and group conditions
- Use COUNT and SUM in one report
- Read the stages of an aggregate query
The idea
WHERE filters individual rows before grouping. HAVING filters groups after aggregates such as COUNT or SUM have been calculated.
SELECT language, COUNT(*) AS learners
FROM learners
GROUP BY language
HAVING COUNT(*) > 1;
01Follow the logical stages
Start from learners, group the rows by language, count each group, and add its XP. HAVING decides which groups remain. ORDER BY then arranges the result.
02Explain the example data
Python has Sam and Mia, totaling 430 XP. JavaScript has Alex and Jordan, totaling 210. SQL has only Lee, so its group does not satisfy the condition.
Your turn
language and SUM(xp). Sort the totals from highest to lowest.What the checks look for
- Returns Python (430) and JavaScript (210)
Take this with you
Use HAVING when the condition depends on the whole group.