10. MySQL Part 1: Install, Create, Insert and SELECT
10.8 Aggregate Functions, GROUP BY and HAVING
Aggregate functions anek rows varun ek uttar kaadhtat. GROUP BY rows gat-gat karto, HAVING gatanvar filter lavto.
SELECT COUNT(*) AS total_students FROM students;
SELECT COUNT(email) FROM students; -- ignores NULLs → 9
SELECT SUM(fees_paid), AVG(fees_paid), MIN(age), MAX(age) FROM students;
SELECT city, COUNT(*) AS students FROM students GROUP BY city;
SELECT city, SUM(fees_paid) AS total_fees FROM students
GROUP BY city ORDER BY total_fees DESC;
SELECT city, COUNT(*) AS students FROM students
GROUP BY city HAVING COUNT(*) >= 2; -- only cities with 2+ students
SELECT city, AVG(age) AS avg_age FROM students
WHERE fees_paid > 0 -- filter rows first
GROUP BY city
HAVING AVG(age) > 23; -- then filter groups
| Clause | Filters | Can use aggregates? |
|---|---|---|
WHERE |
Individual rows, before grouping | No |
HAVING |
Groups, after grouping | Yes |
Order of execution: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
Ravindra Bagale's Tip
WHERE COUNT(*) > 1 lihinare khup students error baghtat. WHERE grouping chya aadhi chalto, tevha COUNT astitvatach nasto – aggregate var filter mhanje HAVING. Execution order cha kram ekda lihun kaadha, mag kadhi confuse honar nahi.
Practice task
Show the number of students and total fees per city; only cities whose total fees exceed 20000; and the average score per course from enrollments.