SQL HAVING Clause

The HAVING clause in SQL is used to filter groups created by GROUP BY. While the WHERE clause filters individual rows, HAVING filters aggregated results.

📌 Syntax

SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING aggregate_function(column2) condition;

📊 Example Table: users

id | name    | age | city
---+---------+-----+---------
1  | Alice   | 22  | New York
2  | Bob     | 30  | London
3  | Charlie | 18  | Sydney
4  | Diana   | 27  | Toronto
5  | Ethan   | 35  | Paris
6  | Frank   | 28  | London
7  | Grace   | 24  | Paris

🔍 Example 1: Cities with More Than 1 User

SELECT city, COUNT(*) AS user_count
FROM users
GROUP BY city
HAVING COUNT(*) > 1;

🔍 Example 2: Average Age Greater Than 25

Filter groups where the average age of users in a city is above 25:

SELECT city, AVG(age) AS avg_age
FROM users
GROUP BY city
HAVING AVG(age) > 25;

🔍 Example 3: Combining HAVING with WHERE

First filter rows with WHERE, then aggregate and filter with HAVING:

SELECT city, COUNT(*) AS user_count
FROM users
WHERE age > 20
GROUP BY city
HAVING COUNT(*) >= 2;

⚡ Best Practices

  • Use WHERE to filter rows before aggregation for efficiency.
  • Use HAVING only to filter aggregated results.
  • Combine with GROUP BY and ORDER BY for clear reporting.

📝 Summary

The HAVING clause allows filtering of grouped results after aggregation. It complements GROUP BY and is essential for reporting and analytics where only groups meeting specific criteria should be included.

🚀 Next Steps

Next, we will explore SQL JOINs, which allow you to combine data from multiple tables to perform complex relational queries.