While basic aggregate functions compute a single summary across the entire table, real-world business reports require metrics broken down by category (e.g., "Average GPA per course" or "Total sales per region"). The GROUP BY clause collapses rows sharing identical values in specified columns into summary rows.
When the database engine executes GROUP BY course, it organizes the incoming rows into buckets by unique course name, and then evaluates aggregate functions separately for each bucket:
-- Calculate total students and average GPA per course
SELECT
course,
COUNT(*) AS total_students,
ROUND(AVG(gpa), 2) AS average_gpa
FROM students
GROUP BY course
ORDER BY average_gpa DESC;
| course | total_students | average_gpa |
|---|---|---|
| B.Tech | 1 | 3.92 |
| BCA | 2 | 3.80 |
| MCA | 1 | 3.68 |
You can group by multiple attributes to drill down into subcategories:
-- Calculate total payroll per department AND job title
SELECT
department,
job_title,
COUNT(emp_id) AS head_count,
SUM(salary) AS total_payroll
FROM employees
GROUP BY department, job_title
ORDER BY department ASC, total_payroll DESC;
GROUP BY and not inside an aggregate, the database doesn't know which row's value to pick for that bucket! Always group by all non-aggregated columns.
Next, let us learn how to filter grouped aggregates using the SQL HAVING Clause!
Every column appearing in the SELECT list must either: (1) be explicitly listed in the GROUP BY clause, or (2) be wrapped inside an aggregate function (e.g., COUNT, SUM, AVG). Violating this causes an ONLY_FULL_GROUP_BY error in standard ANSI SQL and modern MySQL 8.0.
Yes! Multi-column grouping (e.g., GROUP BY department, job_title) creates nested subgroups, calculating metrics for every unique combination of department and title.
All rows where the grouping column is NULL are grouped together into a single summary bucket.
Proceed to the next class in sequence to build production mastery of relational database architecture.
Continue to Class 32: HAVING Clause → Previous: ← Aggregate Functions | Full Syllabus
Using COUNT, SUM, AVG, MIN, and MAX with GROUP BY.
Filtering pre-aggregate rows (WHERE) vs post-aggregate groups (HAVING).
Aggregating order lines, customer totals, and invoice items.
Accelerating GROUP BY queries using composite B-tree indexes.