πŸ“Š SQL Grouping & Filtering
Estimated reading: 2 minutes 365 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 :
Share

πŸ”Ž SQL HAVING

Or Copy Link

CONTENTS
Scroll to Top