GROUP BY — Summarise Groups in SQL
One result row per category
GROUP BY splits rows into buckets sharing the same value in the grouped column, then aggregates inside each bucket. GROUP BY department turns six employee rows into one row per department with its COUNT/AVG/SUM. Golden rule: every column in SELECT must be either in the GROUP BY or wrapped in an aggregate.
Rows fall into buckets
GROUP BY department: every distinct department value becomes one bucket.
Aggregates compute per bucket
COUNT(*), AVG(salary) etc. run inside each bucket, producing one summary row per group.
Select the group key + aggregates
SELECT department, COUNT(*), AVG(salary) — the golden rule: every column is either the group key or wrapped in an aggregate.
Multiple keys = finer buckets
GROUP BY department, location creates one bucket per (department, location) combination.
Filter rows before, groups after
WHERE filters rows before bucketing; HAVING filters whole groups after — the next topic.
1SELECT department,2 COUNT(*) AS headcount,3 ROUND(AVG(salary), 0) AS avg_salary4FROM employees5GROUP BY department;
| department | headcount | avg_salary |
|---|---|---|
| Engineering | 3 | 83000 |
| Sales | 2 | 55000 |
| Marketing | 1 | 47000 |
Six rows in, three buckets out — Engineering holds Alice/Cynthia/Farid averaging 83k. The visualization drops employees into labelled bins, then computes one summary card per bin.
Headcount per department
The canonical grouping query.
1SELECT department, COUNT(*) AS headcount2FROM employees3GROUP BY department;
| department | headcount |
|---|---|
| Engineering | 3 |
| Sales | 2 |
| Marketing | 1 |
Average per department
An aggregate other than COUNT.
1SELECT department, ROUND(AVG(salary), 0) AS avg_salary2FROM employees3GROUP BY department;
| department | avg_salary |
|---|---|
| Engineering | 83000 |
| Sales | 55000 |
| Marketing | 47000 |
Several aggregates per group
A full summary card per bucket.
1SELECT department,2 COUNT(*) AS headcount,3 ROUND(AVG(salary), 0) AS avg_salary,4 MAX(salary) AS top_salary5FROM employees6GROUP BY department;
| department | headcount | avg_salary | top_salary |
|---|---|---|---|
| Engineering | 3 | 83000 | 91000 |
| Sales | 2 | 55000 | 58000 |
| Marketing | 1 | 47000 | 47000 |
Group by an expression
Buckets can come from computed values.
1SELECT CASE WHEN salary >= 80000 THEN 'high'2 WHEN salary >= 60000 THEN 'mid'3 ELSE 'low' END AS band,4 COUNT(*) AS n5FROM employees6GROUP BY band;
| band | n |
|---|---|
| high | 2 |
| mid | 1 |
| low | 3 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.