SQL HAVING Clause
intermediateaggregation
2 min read
What is HAVING?
HAVING filters groups created by GROUP BY. While WHERE filters individual rows before grouping, HAVING filters groups after aggregation.
Syntax
SELECT column, AGGREGATE(other_column)
FROM table_name
GROUP BY column
HAVING AGGREGATE(other_column) condition;When to Use
- Showing only departments with more than 5 employees
- Finding products with total sales above a threshold
- Any post-aggregation filter
Key Points
- WHERE vs HAVING — WHERE filters rows before GROUP BY. HAVING filters groups after.
- Aggregate Conditions — HAVING typically references aggregate functions:
HAVING COUNT(*) > 5. - Execution Order — FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY.
- Without GROUP BY — Technically HAVING can be used without GROUP BY, treating the entire result as one group.
- Combine Both — Use WHERE to reduce the dataset first, then HAVING to filter aggregated results.
Guided Practice
Solve the challenge below. Use hints when stuck and check your answer for instant feedback.
Practice challengeGuided learning mode
SQL HAVING Clause Challenge
Write a query that find grades that have more than 3 students.
Expected result
Only grades with more than 3 students appear.
Hidden checks
- Returned rows and values
- Output columns and result shape
- Final database state after the query runs
Lesson guidance
What is HAVING?
Initializing database...Each run starts from fresh sample data.
More Examples
High-spending students
Find students who have spent more than 500 total.
Initializing database...Each run starts from fresh sample data.
Frequently Asked Questions
Can I use WHERE instead of HAVING?
No. WHERE cannot reference aggregate functions because it runs before GROUP BY.
What is the SQL execution order with HAVING?
FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY -> LIMIT.