Class 31 of 58 • Aggregation & Grouping

SQL GROUP BY Clause: Categorical Summaries & Grouping

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.


The Mechanics of GROUP BY

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

Multi-Column Grouping (Nested Subgroups)

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;
Understanding ONLY_FULL_GROUP_BY: If you select a column that is not part of the 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!


Frequently Asked Questions (FAQ)

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.

Next Step in Your SQL Database Learning Path:

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


Related SQL Masterclass Lessons & Recommended Next Topics

Aggregate Functions →

Using COUNT, SUM, AVG, MIN, and MAX with GROUP BY.

HAVING vs WHERE →

Filtering pre-aggregate rows (WHERE) vs post-aggregate groups (HAVING).

Grouping Joined Tables →

Aggregating order lines, customer totals, and invoice items.

Index-Driven Grouping →

Accelerating GROUP BY queries using composite B-tree indexes.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!