MySQL GROUP BY and HAVING
GROUP BY puts rows with the same value in a column into groups, and an aggregate function calculates one value for each group.
SELECT city, COUNT(*) AS students, AVG(marks) AS average_marks
FROM students
GROUP BY city
ORDER BY city;
Result
| city | students | average_marks |
|---|---|---|
| Delhi | 2 | 75.0000 |
| Jaipur | 1 | 88.0000 |
| Mumbai | 2 | 68.5000 |
| Pune | 1 | 78.0000 |
There is one row for each city. Delhi has two students with an average of (85 + 65) / 2 = 75.
HAVING: filter the groups
WHERE filters rows before grouping. HAVING filters the groups after grouping, so it can use aggregate functions.
SELECT city, COUNT(*) AS students
FROM students
GROUP BY city
HAVING COUNT(*) > 1
ORDER BY city;
Cities with more than one student
| city | students |
|---|---|
| Delhi | 2 |
| Mumbai | 2 |
WHERE and HAVING together
SELECT city, AVG(marks) AS average_marks
FROM students
WHERE marks > 50
GROUP BY city
HAVING AVG(marks) > 80
ORDER BY city;
Result
| city | average_marks |
|---|---|
| Jaipur | 88.0000 |
| Mumbai | 92.0000 |
First the rows with marks 50 or less are removed (Neha). Then the cities are grouped. Mumbai now has only Maria (92), so its average is 92. Delhi (75) and Pune (78) are not above 80.
Order of the clauses
SELECT ... FROM ... WHERE ... GROUP BY ... HAVING ... ORDER BY ... LIMIT ...
Note:
Every column in the SELECT list that is not inside an aggregate function must also be in GROUP BY. Otherwise MySQL gives an error in strict mode.
Summary
GROUP BYmakes groups, aggregates calculate per group.HAVINGfilters groups,WHEREfilters rows.- Next: MySQL JOINs.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |