Browse SQL Topics โ–ผ

GROUP BY

๐Ÿ“‚ Summarizing Data ๐Ÿ“˜ Lesson 37 of 81

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:

FunctionWhat It CalculatesExample
COUNT(*)Total number of rowsCOUNT(*) AS total_orders
COUNT(column)Number of non-NULL valuesCOUNT(email) AS verified_users
SUM(column)Total sum of all numbersSUM(amount) AS total_revenue
AVG(column)Arithmetic meanAVG(rating) AS average_rating
MIN(column)Smallest value (dates, numbers, text)MIN(price) AS cheapest_item
MAX(column)Largest valueMAX(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 SELECT clause must appear in the GROUP BY clause.

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

  1. COUNT(*) vs COUNT(column) with NULLs: COUNT(*) counts every row in the group. COUNT(bonus) counts only rows where bonus is not NULL. If 8 out of 10 workers received no bonus, COUNT(*) returns 10, while COUNT(bonus) returns 2.
  2. Forgetting to group by all non-aggregate columns: If you write SELECT country, city, SUM(sales), your GROUP BY must include both: GROUP BY country, city.
  3. Putting group conditions in WHERE: Remember that WHERE can never contain SUM(), AVG(), or COUNT(). Move all aggregate tests into HAVING.

Next Steps

Master this concept to build a rock-solid foundation. Next, proceed to groupby-multiple-columns.

Test your understanding of GROUP BY

Quick interactive practice questions with instant feedback.

Take Quiz โ†’