MySQL + SQL · Lesson 56

GROUP BY and HAVING

GROUP BY — Summarise per Group

GROUP BY splits rows into groups and applies an aggregate to each group.

SELECT class, COUNT(*) AS total
FROM students
GROUP BY class;
Shows how many students are in each class.

Average per Group

SELECT class, AVG(marks) AS avg_marks
FROM students
GROUP BY class;

HAVING — Filter Groups

HAVING filters groups after aggregation (WHERE filters rows before).

SELECT class, AVG(marks) AS avg_marks
FROM students
GROUP BY class
HAVING AVG(marks) >= 80;
Only classes whose average is 80 or more.

WHERE vs HAVING

WHERE filters individual rows BEFORE grouping. HAVING filters groups AFTER grouping. Aggregate conditions (like AVG) must use HAVING.

Summary

  • GROUP BY makes groups; aggregates run per group.
  • HAVING filters groups; WHERE filters rows before grouping.
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

WhatsApp