Advertisement
Google Ad Slot: content-top
MySQL HAVING
MySQL HAVING Clause
The HAVING clause in MySQL is used to filter the results of a GROUP BY operation.
- Unlike
WHERE, which filters rows before grouping, HAVINGfilters data after the aggregation using functions likeSUM(),COUNT(),AVG(),MAX(), andMIN().
HAVING Syntax
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 likeSUM(),COUNT(),AVG(), etc.HAVING→ Filter the results of the aggregation.
MySQL HAVING Examples
We have two tables:
students Table
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 |
courses Table
course_name |
course_name |
|---|---|
101 |
Math |
102 |
Science |
103 |
History |
104 |
English |
The following SQL statement find cities with average score greater than 80.
Output:
city |
avg_score |
|---|---|
Delhi |
90.0 |
Explanation:
AVG(score)calculates the average score per city.HAVING AVG(score) > 80filters the cities where the average score is above 80.
HAVING Examples with join
The following SQL statement find courses with average score greater than 80.
Output:
course_name |
avg_score |
|---|---|
History |
85.0 |
Explanation:
JOINcombinesstudentsandcoursesbased oncourse_id.GROUP BYgroups the data bycourse_name.AVG(score)calculates the average score for each course.HAVINGfilters courses with an average score greater than 80.