π 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 :
