100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
SQL Mastery
30 minbeginner

HAVING — Filtering Groups

WHERE filters individual rows, but once you have grouped data, you often need to filter the groups themselves: only teams that scored over five hundred runs, only players with more than ten innings, only venues hosting at least three matches. These conditions are about aggregate values that do not exist until grouping completes, and HAVING is the clause built precisely for them.

Trying to express a group-level condition in WHERE simply fails, because WHERE runs before any aggregate is computed. HAVING fills that gap by applying its condition after GROUP BY has formed the groups and the aggregates have been calculated. It is, in effect, the WHERE clause for summary rows rather than raw rows, operating one level higher in the query.

Understanding the clean division of labour between WHERE and HAVING is what separates analysts who fight the engine from those who flow with it. Each clause has a distinct job at a distinct stage, and using the right one not only makes queries correct but often makes them dramatically faster, since filtering rows early in WHERE shrinks the work HAVING must consider later.

Analogy🏏Cricket
🏏 Think of it like cricket: Imagine the end of an IPL innings when the scorer announces the team's final total. Just as the scorer does not read out all one hundred and twenty individual deliveries but instead sums them into a single team score, SUM folds many row values into one number. Just as the commentator reports the highest individual score, the average partnership, and the number of wickets, MAX, AVG, and COUNT each summarise the innings differently. Just as a not-out batsman with no deliveries faced does not lower the team average, aggregates skip NULLs when computing. Just as the announcement is one figure no matter whether the innings had fifty deliveries or two hundred and fifty, an aggregate collapses any number of rows into a single result. This reveals why summaries answer the questions about the whole that individual deliveries cannot.
Lesson 9 of 35
0% complete