Aggregation: GROUP BY and HAVING · Lesson 11 of 30
SQL GROUP BY Clause
An aggregate on its own gives one number for the whole table. GROUP BY gives one number per group: salary per department, orders per status, revenue per month. It's how SQL builds every "breakdown" report, and it's asked about in nearly every SQL interview.
In this lesson
- How GROUP BY splits rows into groups
- Grouping by several columns and by expressions
- The rule for what you may SELECT
- Sorting groups and finding the top group
One row per group
SELECT department,
COUNT(*) AS people,
SUM(salary) AS payroll,
ROUND(AVG(salary)) AS avg_salary
FROM employees
GROUP BY department
ORDER BY department;
+-------------+--------+---------+------------+ | department | people | payroll | avg_salary | +-------------+--------+---------+------------+ | Engineering | 4 | 515000 | 128750 | | HR | 2 | 155000 | 77500 | | Management | 1 | 250000 | 250000 | | Sales | 3 | 303000 | 101000 | +-------------+--------+---------+------------+
What GROUP BY department does
- Splitrows into piles: Engineering (4), HR (2), Management (1), Sales (3)
- Aggregate each pileCOUNT, SUM and AVG run separately per pile
- Return one row per pilethe group key plus its aggregates
The SELECT rule
Every column in the SELECT list must either be in GROUP BY or be inside an aggregate. This query is invalid:
SELECT department, name, MAX(salary) -- which "name"? a group has several
FROM employees
GROUP BY department;
-- MySQL 8: ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP BY clause
-- and contains nonaggregated column 'name' … incompatible with sql_mode=only_full_group_by
A department has several names, so SQL can't know which one to show. Older MySQL versions (and MariaDB by default) return an arbitrary name instead of an error – a silent bug. To get "the highest-paid person per department" you need a join, subquery or window function (chapters 5–7).
Grouping by several columns
SELECT customer_id, status, COUNT(*) AS orders
FROM orders
WHERE customer_id IN (1, 2, 3, 4)
GROUP BY customer_id, status
ORDER BY customer_id, status;
+-------------+-----------+--------+ | customer_id | status | orders | +-------------+-----------+--------+ | 1 | delivered | 2 | | 1 | shipped | 1 | | 2 | delivered | 2 | | 3 | cancelled | 1 | | 3 | delivered | 1 | | 4 | delivered | 1 | | 4 | pending | 1 | +-------------+-----------+--------+
Each unique combination of the grouped columns becomes one row – customer 1 has a "delivered" group and a "shipped" group.
Grouping by an expression: revenue per month
SELECT DATE_FORMAT(o.order_date, '%Y-%m') AS month,
COUNT(DISTINCT o.order_id) AS orders,
SUM(i.quantity * i.unit_price) AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY month
ORDER BY month;
+---------+--------+---------+ | month | orders | revenue | +---------+--------+---------+ | 2025-08 | 3 | 4138.00 | | 2025-09 | 2 | 4697.00 | | 2025-10 | 3 | 2738.00 | | 2025-11 | 3 | 3798.00 | +---------+--------+---------+
The JOIN combines each order with its items (chapter 5). MySQL lets you group by a SELECT alias like month; in standard SQL you repeat the expression: GROUP BY DATE_FORMAT(o.order_date, '%Y-%m').
Sorting groups and the top group
-- Best-selling products by units sold
SELECT product_id, SUM(quantity) AS units_sold
FROM order_items
GROUP BY product_id
ORDER BY units_sold DESC, product_id
LIMIT 3;
+------------+------------+ | product_id | units_sold | +------------+------------+ | 7 | 7 | | 6 | 5 | | 1 | 4 | +------------+------------+
NULL is a group too
SELECT category_id, COUNT(*) AS products
FROM products
GROUP BY category_id
ORDER BY category_id;
+-------------+----------+ | category_id | products | +-------------+----------+ | NULL | 1 | | 1 | 4 | | 2 | 3 | | 3 | 2 | +-------------+----------+
All rows with a NULL category form one group. Category 4 (Fitness) doesn't appear at all – GROUP BY only groups rows that exist. Showing categories with zero products needs a LEFT JOIN (chapter 5).
Practice
Try it yourself
Count orders per status, most common first.
Show solution
SELECT status, COUNT(*) AS orders FROM orders GROUP BY status ORDER BY orders DESC, status;+-----------+--------+ | status | orders | +-----------+--------+ | delivered | 7 | | pending | 2 | | shipped | 2 | | cancelled | 1 | +-----------+--------+
For each order, show the number of different products and the order total, biggest orders first (top 4).
Show solution
SELECT order_id, COUNT(*) AS products, SUM(quantity * unit_price) AS total FROM order_items GROUP BY order_id ORDER BY total DESC LIMIT 4;+----------+----------+---------+ | order_id | products | total | +----------+----------+---------+ | 105 | 2 | 3697.00 | | 102 | 1 | 2499.00 | | 111 | 2 | 2098.00 | | 104 | 1 | 1499.00 | +----------+----------+---------+
Quick check
How many rows does a GROUP BY query return?
One per distinct value (or combination of values) of the grouped columns.
Can you SELECT a column that is neither grouped nor aggregated?
No – it's an error under ONLY_FULL_GROUP_BY (the MySQL 8 default) and ambiguous everywhere.
Are NULLs grouped together?
Yes, all NULLs form a single group.
Summary
- GROUP BY splits rows into groups and aggregates each group separately.
- SELECT only grouped columns and aggregates; group by several columns or expressions as needed.
- NULL forms its own group; empty categories need a LEFT JOIN to appear.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.