GROUP BY
Collapse rows into summary groups and calculate metrics with COUNT, SUM, AVG, MIN, and MAX, and filter aggregated groups using HAVING.
If an online retail store receives 500,000 orders every month, company leadership doesnโt want to read 500,000 individual receipt lines.
They need high-level business intelligence:
- โWhat is our total revenue per country?โ
- โHow many products were sold in each category?โ
- โWhat is the average employee salary per department?โ
In SQL, GROUP BY collapses hundreds or thousands of individual rows sharing a common value into a single summary row. It is almost always paired with aggregate functions like COUNT, SUM, and AVG.
The Five Essential Aggregate Functions
Aggregate functions take a collection of multiple numbers and crunch them down into a single summary value:
| Function | What It Calculates | Example |
|---|---|---|
COUNT(*) | Total number of rows | COUNT(*) AS total_orders |
COUNT(column) | Number of non-NULL values | COUNT(email) AS verified_users |
SUM(column) | Total sum of all numbers | SUM(amount) AS total_revenue |
AVG(column) | Arithmetic mean | AVG(rating) AS average_rating |
MIN(column) | Smallest value (dates, numbers, text) | MIN(price) AS cheapest_item |
MAX(column) | Largest value | MAX(created_at) AS latest_signup |
Without GROUP BY, an aggregate function summarizes the entire table into a single number:
SELECT COUNT(*) AS total_employees, AVG(salary) AS company_avg_salary
FROM employees;
Grouping Rows with GROUP BY
To break down the numbers by department or city, add GROUP BY:
SELECT department, COUNT(*) AS num_staff, AVG(salary) AS avg_pay
FROM employees
GROUP BY department;
Given this input data:
TABLE: employees
โโโโโโฌโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโฌโโโโโโโโโ
โ id โ name โ department โ salary โ
โโโโโโผโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโผโโโโโโโโโค
โ 1 โ Alice Johnson โ Engineering โ 90000 โ
โ 2 โ Bob Smith โ Sales โ 60000 โ
โ 3 โ Carlos Ruiz โ Engineering โ 110000 โ
โ 4 โ Dana White โ Sales โ 70000 โ
โ 5 โ Evan Green โ Engineering โ 85000 โ
โโโโโโดโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโดโโโโโโโโโ
The database groups all rows with matching departments together, calculates the counts and averages, and returns two summary rows:
โโโโโโโโโโโโโโโฌโโโโโโโโโโโโฌโโโโโโโโโโ
โ department โ num_staff โ avg_pay โ
โโโโโโโโโโโโโโโผโโโโโโโโโโโโผโโโโโโโโโโค
โ Engineering โ 3 โ 95000 โ
โ Sales โ 2 โ 65000 โ
โโโโโโโโโโโโโโโดโโโโโโโโโโโโดโโโโโโโโโโ
The Cardinal Rule of GROUP BY
[!IMPORTANT] Every non-aggregated column in your
SELECTclause must appear in theGROUP BYclause.
Look at this invalid query:
-- FATAL ERROR in standard SQL:
SELECT department, name, AVG(salary)
FROM employees
GROUP BY department;
Why does this fail?
Because there is only one summary row for Engineering, but there are three different employee names (Alice, Carlos, Evan). The database has no logical way of knowing which personโs name to put in that single cell!
If a column is not inside an aggregate function like COUNT() or AVG(), you must group by it.
Filtering Groups with HAVING vs WHERE
One of the most common mistakes in database engineering is trying to filter summary metrics inside WHERE:
-- SYNTAX ERROR: Aggregate functions cannot appear in WHERE!
SELECT department, COUNT(*)
FROM employees
WHERE COUNT(*) > 5
GROUP BY department;
Why does this crash? Because WHERE runs before groups are created. At the time WHERE examines the table, the counts do not exist yet!
To filter summary groups, use the HAVING clause, which runs after grouping and aggregation:
SELECT department, COUNT(*) AS team_size, AVG(salary) AS avg_sal
FROM employees
WHERE status = 'active' -- 1. Discard inactive employees first
GROUP BY department -- 2. Group the remaining active workers
HAVING COUNT(*) >= 2 -- 3. Keep only departments with 2+ workers
ORDER BY avg_sal DESC; -- 4. Sort the qualifying departments
Comparison Summary
WHERE: Filters raw, individual records before grouping. Works on standard columns (WHERE status = 'active').HAVING: Filters summarized groups after aggregation. Works on aggregate calculations (HAVING COUNT(*) > 5,HAVING SUM(revenue) >= 100000).
The Complete SQL Execution Order
Whenever you write a query containing multiple clauses, memorize the sequence in which the database engine actually processes your code:
1. FROM โโโบ Load table(s)
2. WHERE โโโบ Filter individual rows
3. GROUP BY โโโบ Collapse rows into summary groups
4. HAVING โโโบ Filter aggregated groups
5. SELECT โโโบ Compute columns and aliases
6. ORDER BY โโโบ Sort the final output
7. LIMIT โโโบ Restrict final row count
Common Traps to Avoid
COUNT(*)vsCOUNT(column)withNULLs:COUNT(*)counts every row in the group.COUNT(bonus)counts only rows wherebonusis notNULL. If 8 out of 10 workers received no bonus,COUNT(*)returns 10, whileCOUNT(bonus)returns 2.- Forgetting to group by all non-aggregate columns: If you write
SELECT country, city, SUM(sales), yourGROUP BYmust include both:GROUP BY country, city. - Putting group conditions in
WHERE: Remember thatWHEREcan never containSUM(),AVG(), orCOUNT(). Move all aggregate tests intoHAVING.
Next Steps
Master this concept to build a rock-solid foundation. Next, proceed to groupby-multiple-columns.