SQL HAVING β Filter Grouped Results After Aggregation
Introduction β What is SQL HAVING?
The HAVING clause in SQL is used to filter aggregated results after a GROUP BY operation. Unlike WHERE, which filters individual rows before grouping, HAVING applies conditions to grouped rows.
In this guide, you’ll learn:
- Syntax and difference between
WHEREandHAVING - How to filter results using aggregate functions
- Best practices for using
HAVINGwithGROUP BY
1. HAVING Syntax
SELECT column, AGG_FUNCTION(column)
FROM table
GROUP BY column
HAVING AGG_FUNCTION(column) condition;
Used to filter grouped results based on aggregation.
2. Example β Filter Groups by Total
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 1000;
Shows customers who spent more than $1,000.
3. WHERE vs HAVING
| Clause | Filters Before Grouping | Filters After Grouping | Supports Aggregates |
|---|---|---|---|
| WHERE | |||
| HAVING |
4. Using WHERE with HAVING Together
SELECT department, AVG(salary) AS avg_salary
FROM employees
WHERE salary > 0
GROUP BY department
HAVING AVG(salary) > 50000;
Filters low salaries early with WHERE, then filters high-average groups with HAVING.
5. HAVING with COUNT(), MAX(), MIN()
SELECT status, COUNT(*) AS total
FROM orders
GROUP BY status
HAVING COUNT(*) > 10;
Keeps only order statuses that appear more than 10 times.
Best Practices
| Recommended | Avoid This |
|---|---|
Use HAVING for aggregate conditions | Using WHERE with aggregate functions |
Combine WHERE and HAVING efficiently | Filtering grouped data too late |
| Use aliases for readability | Repeating full expressions |
Summary β Recap & Next Steps
The HAVING clause lets you refine grouped results, filtering by aggregated values. Itβs essential for analytics and summary queries.
Key Takeaways:
- Use
HAVINGafterGROUP BY - Required when filtering with
COUNT(),SUM(),AVG(), etc. - Combine with
WHEREfor row-level filtering
Real-World Relevance:
Used in reports, dashboards, business summaries, and performance KPIs.
Next: Explore advanced grouping tools like ROLLUP, CUBE, and WINDOW FUNCTIONS.
FAQ β SQL HAVING
What is the difference between HAVING and WHERE?
WHERE filters rows before grouping. HAVING filters after aggregation.
Can I use HAVING without GROUP BY?
Yesβbut only if used with an aggregate function.
Do aliases work in HAVING?
Not in all databases. Itβs safer to repeat the full aggregate.
Can I use HAVING with multiple conditions?
Yes, combine them with AND/OR just like WHERE.
Share Now :
