🔍
👶 Kids📝 Blog About Contact 🚀 Get Started Free

SQL – HAVING

Filter grouped results using HAVING — the WHERE clause for aggregate functions.

WHERE cannot filter on aggregate functions — you cannot write WHERE COUNT(*) > 3 because COUNT is calculated after rows are grouped. That is where HAVING comes in. It filters grouped results the same way WHERE filters individual rows — but it runs after grouping and aggregation.

A good memory trick: WHERE filters before grouping (on raw data), HAVING filters after grouping (on aggregate results). They can even appear in the same query together.

WHERE vs HAVING

SELECT city, AVG(score)
FROM students
WHERE  age > 20          -- Filters rows BEFORE grouping
GROUP BY city
HAVING AVG(score) > 80;  -- Filters groups AFTER aggregating

Try It Yourself — Interactive SQL Editor

Edit the query below and click Run Query ▶ to see live results powered by SQLite running directly in your browser.

SQLite – edit & run
Results
← Click Run Query ▶ to see results

Key Points

  • HAVING filters GROUP BY results — WHERE filters individual rows
  • HAVING can use aggregate functions; WHERE cannot
  • HAVING runs after GROUP BY; WHERE runs before
  • Both WHERE and HAVING can exist in the same query

Pro Tip from CodesCompiler: The best way to learn SQL is to break things intentionally — modify the query above, change the WHERE conditions, try different columns. Every error teaches you something the docs cannot.

In the next lesson, we continue exploring SQL’s powerful feature set to build your database mastery.