Having and aggregate filtering
HAVING is WHERE for groups. WHERE filters individual rows before grouping. HAVING filters entire groups after aggregation. You cannot use WHERE COUNT(*) > 100 because COUNT does not exist yet when WHERE runs.
-- Only states with more than 5,000 customers
SELECT
customer_state,
COUNT(*) AS customer_count
FROM customers
GROUP BY customer_state
HAVING COUNT(*) > 5000
ORDER BY customer_count DESC;HAVING filters groups after aggregation. Only groups where the count exceeds 5,000 appear in the result.
No! WHERE runs before GROUP BY, so aggregate functions like COUNT do not exist yet. HAVING runs after GROUP BY when aggregates are available. Rule of thumb: filter on raw column values with WHERE, filter on aggregate results with HAVING.
Ordering exercise: Full SQL execution order
Loading practice…
Fill in the blanks: Complete the having query
Loading practice…
Quiz: Quiz
Loading practice…
Code playground: High-value categories
Loading practice…
Timed quiz: Aggregation speed round
Loading practice…