πŸ“Š SQL Grouping & Filtering
Estimated reading: 2 minutes 28 views

πŸ”Ž 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 WHERE and HAVING
  • How to filter results using aggregate functions
  • Best practices for using HAVING with GROUP 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

ClauseFilters Before GroupingFilters After GroupingSupports 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 conditionsUsing WHERE with aggregate functions
Combine WHERE and HAVING efficientlyFiltering grouped data too late
Use aliases for readabilityRepeating 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 HAVING after GROUP BY
  • Required when filtering with COUNT(), SUM(), AVG(), etc.
  • Combine with WHERE for 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ”Ž SQL HAVING

Or Copy Link

CONTENTS
Scroll to Top