SQL GROUP BY
GROUP BY splits rows into groups that share a value, then runs aggregate functions once per group. It answers questions like “how many drinks in each category?”.
Updated December 1, 2026
Syntax
SELECT group_column, AGGREGATE(column)
FROM table_name
GROUP BY group_column;
Count and average per group
One result row per category.
SELECT category,
COUNT(*) AS drinks,
ROUND(AVG(price), 2) AS avg_price
FROM drinks
GROUP BY category;
| category | drinks | avg_price |
|---|---|---|
| coffee | 5 | 4.3 |
| other | 2 | 3.75 |
| tea | 3 | 4.42 |
Group and sort
Units sold of each product, best sellers first.
SELECT product_id, SUM(quantity) AS units
FROM order_items
GROUP BY product_id
ORDER BY units DESC, product_id;
| product_id | units |
|---|---|
| 7 | 5 |
| 3 | 4 |
| 1 | 3 |
| 6 | 3 |
| 2 | 2 |
| 4 | 2 |
Group by several columns
Each unique combination becomes a group: here, every job title within each department.
SELECT department_id, title, COUNT(*) AS people
FROM employees
WHERE department_id IN (1, 2)
GROUP BY department_id, title
ORDER BY department_id, title;
| department_id | title | people |
|---|---|---|
| 1 | Engineer | 2 |
| 1 | Senior Engineer | 1 |
| 1 | Staff Engineer | 1 |
| 1 | VP Engineering | 1 |
| 2 | Account Executive | 2 |
| 2 | Head of Sales | 1 |
| 2 | Sales Associate | 1 |
Common mistakes
- Selecting a column that isn’t grouped or aggregated. Every selected column must be in
GROUP BYor inside an aggregate. - Filtering groups with
WHERE.WHEREfilters rows before grouping;HAVINGfilters groups after. - Expecting groups in a particular order. Add
ORDER BY.
Practice GROUP BY interactively
Write real queries in your browser and get instant feedback in the lesson “GROUP BY” (Unit 4). New learners can start free from the first lesson.
Frequently asked questions
Does GROUP BY include NULLs?
Yes. All NULLs fall into a single group, shown with NULL as its value.
Can I group by an expression?
Yes, for example GROUP BY strftime('%Y-%m', ordered_on) to group by month. See date functions.