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
Many students who write WHERE COUNT(*) > 1 see an error. WHERE runs before grouping, when COUNT doesn't exist yet – a filter on an aggregate means HAVING. Write down the execution order once, and you'll never be confused again.
Ravindra Bagale's Tip – मराठी
WHERE COUNT(*) > 1 लिहिणारे बरेच students error बघतात. WHERE grouping च्या आधी चालतो, तेव्हा COUNT अस्तित्वातच नसतो – aggregate वर filter म्हणजे HAVING. Execution order चा क्रम एकदा लिहून काढा, मग कधी confuse होणार नाही.
Ravindra Bagale's Tip – हिंदी
WHERE COUNT(*) > 1 लिखने वाले बहुत से students error देखते हैं. WHERE grouping से पहले चलता है, तब COUNT होता ही नहीं – aggregate पर filter यानी HAVING. Execution order का क्रम एक बार लिख लो, फिर कभी confuse नहीं होगे.
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.