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 BY makes groups, aggregates calculate per group.
  • HAVING filters groups, WHERE filters rows.
  • Next: MySQL JOINs.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a query to show the total balance using debit and credit entries
Write a query to show the count of students by city
Write a query to show the average marks of each city
Write a query to find the cities that have more than one student
Write a query to fetch the number of students from Delhi
Interview Questions & Answers
What is the difference between WHERE and HAVING?
What are aggregate functions in MySQL?
How to find duplicate records in a MySQL table?
How to count the number of rows in a table in MySQL?