Learn SQL
-- aggregations.group_by

GROUP BY — Summarise Groups in SQL

One result row per category

--concept

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.

--how it works
1

Rows fall into buckets

GROUP BY department: every distinct department value becomes one bucket.

2

Aggregates compute per bucket

COUNT(*), AVG(salary) etc. run inside each bucket, producing one summary row per group.

3

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.

4

Multiple keys = finer buckets

GROUP BY department, location creates one bucket per (department, location) combination.

5

Filter rows before, groups after

WHERE filters rows before bucketing; HAVING filters whole groups after — the next topic.

--visualization
aggregate per bucket:
EngineeringAlice · 85,000Cynthia · 91,000Farid · 73,000SalesBob · 52,000Elena · 58,000MarketingDavid · 47,000six rows in → three grouped rows out
Stage 1 / 5
GROUP BY department — every employee drops into their department's bucket.
--example
query.sql
1SELECT department,
2 COUNT(*) AS headcount,
3 ROUND(AVG(salary), 0) AS avg_salary
4FROM employees
5GROUP BY department;
Result
departmentheadcountavg_salary
Engineering383000
Sales255000
Marketing147000

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.

--variants

Headcount per department

The canonical grouping query.

query.sql
1SELECT department, COUNT(*) AS headcount
2FROM employees
3GROUP BY department;
Result
departmentheadcount
Engineering3
Sales2
Marketing1
1Three buckets form: Engineering, Sales, Marketing.
2Rows drop into bins: 3, 2, 1.
3One summary row per bin — 6 rows became 3.

Average per department

An aggregate other than COUNT.

query.sql
1SELECT department, ROUND(AVG(salary), 0) AS avg_salary
2FROM employees
3GROUP BY department;
Result
departmentavg_salary
Engineering83000
Sales55000
Marketing47000
1Engineering: (85000+91000+73000)/3 = 83000.
2Sales: (52000+58000)/2 = 55000; Marketing: 47000.
3Same buckets, different aggregate — the machinery is identical.

Several aggregates per group

A full summary card per bucket.

query.sql
1SELECT department,
2 COUNT(*) AS headcount,
3 ROUND(AVG(salary), 0) AS avg_salary,
4 MAX(salary) AS top_salary
5FROM employees
6GROUP BY department;
Result
departmentheadcountavg_salarytop_salary
Engineering38300091000
Sales25500058000
Marketing14700047000
1Three aggregates evaluated independently per bucket.
2Engineering: 3 people, avg 83000, top 91000.
3One scan produces the whole report.

Group by an expression

Buckets can come from computed values.

query.sql
1SELECT CASE WHEN salary >= 80000 THEN 'high'
2 WHEN salary >= 60000 THEN 'mid'
3 ELSE 'low' END AS band,
4 COUNT(*) AS n
5FROM employees
6GROUP BY band;
Result
bandn
high2
mid1
low3
1The CASE buckets rows by salary tier: high ≥80k (2), mid 60–79k (1), low <60k (3).
2GROUP BY band — the SELECT alias — collapses to one row per tier.
3Expressions as group keys unlock cohorting: by year, by tier, by first letter.
--key facts
Golden rulenon-aggregated SELECT columns must appear in GROUP BY
Bucket countresult rows = number of distinct values in the grouped column
NULL bucketNULLs form their own group in most engines
--use cases
Every dashboard breakdown: sales per region, users per country
Reporting hierarchies: GROUP BY year, month for trend lines
Cohort analysis via grouped expressions (signup month, tier)
Interview warm-up: "second-highest salary per department"
--under the hood
Engines may hash or sort to build buckets; for big grouped scans, a covering index on (group keys, aggregates) is gold.
The golden rule is enforced (or warned about) everywhere — SELECTing a stray column with GROUP BY is the classic error message you will meet.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.