SQL HAVING clause

SQL Tutorial

Here is a clear, practical, and complete guide to the SQL HAVING clause, including examples and key differences from WHERE.


What the SQL HAVING clause Does

HAVING filters grouped/aggregated results after GROUP BY is applied.

It is similar to WHERE, but:

  • WHERE filters rows BEFORE grouping

  • HAVING filters groups AFTER aggregation


Basic Syntax


 Simple Examples

1. Departments with more than 10 employees


2. Products with total sales above $1,000


3. Classes where the average score is below 70


Using HAVING Without GROUP BY

Most databases allow HAVING even without GROUP BY:

Useful when you want to filter by an aggregate without grouping.


 Combine WHERE + HAVING (Best Practice)

Use WHERE first to reduce data before grouping.

Example: Count high-value orders per customer


 Key Difference: WHERE vs HAVING

ClauseFiltersCan use aggregates?Example
WHEREBefore grouping NoWHERE price > 100
HAVINGAfter groupingYesHAVING SUM(sales) > 1000

 Real-World Examples

Find customers who spent over $10,000 total


Find stores with more than 3 employees


Find categories where the average product price is above $30


 Performance Tips

  •  Use WHERE to filter rows early — boosts performance
  •  Use HAVING only for aggregated conditions
  •  Index columns used in WHERE for best performance
  •  Avoid unnecessary HAVING clauses

You may also like...