MySQL Tutorial
The HAVING clause in MySQL is used to filter the results of a GROUP BY operation.
WHERE, which filters rows before grouping,HAVING filters data after the aggregation using functions like SUM(), COUNT(), AVG(), MAX(), and MIN().SELECT column_name, aggregate_function(column_name) FROM table_name GROUP BY column_name HAVING condition ORDER BY column_name;
column_name → Column to display or group by.aggregate_function() → Functions like SUM(), COUNT(), AVG(), etc.HAVING → Filter the results of the aggregation.We have two tables:
|
student_id |
name |
gender |
city |
age |
score |
course_id |
|
phone_number |
|---|---|---|---|---|---|---|---|---|
|
1 |
Alice |
Female |
Delhi |
20 |
85 |
101 |
NULL |
1234567890 |
|
2 |
Bob |
Male |
Mumbai |
22 |
75 |
NULL |
bob@email.com |
NULL |
|
3 |
Charlie |
Male |
Delhi |
21 |
95 |
102 |
NULL |
NULL |
|
4 |
David |
Male |
Bangalore |
23 |
65 |
101 |
david@email.com |
NULL |
|
5 |
Eve |
Female |
Mumbai |
20 |
80 |
103 |
NULL |
NULL |
|
6 |
Frank |
Male |
Delhi |
22 |
90 |
103 |
NULL |
NULL |
|
7 |
Alice |
Female |
Mumbai |
19 |
60 |
102 |
NULL |
NULL |
|
course_name |
course_name |
|---|---|
|
101 |
Math |
|
102 |
Science |
|
103 |
History |
|
104 |
English |
The following SQL statement find cities with average score greater than 80.
Try it yourself
|
city |
avg_score |
|---|---|
|
Delhi |
90.0 |
AVG(score) calculates the average score per city.HAVING AVG(score) > 80 filters the cities where the average score is above 80.The following SQL statement find courses with average score greater than 80.
Try it yourself
|
course_name |
avg_score |
|---|---|
|
History |
85.0 |
JOIN combines students and courses based on course_id.GROUP BY groups the data by course_name.AVG(score) calculates the average score for each course.HAVING filters courses with an average score greater than 80.