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;
Result on the SQL Café sample data (3 rows)
categorydrinksavg_price
coffee54.3
other23.75
tea34.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;
Result on the Desk & Co. (online store) sample data (8 rows, first 6 shown)
product_idunits
75
34
13
63
22
42

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;
Result on the Acme Co. (company data) sample data (7 rows)
department_idtitlepeople
1Engineer2
1Senior Engineer1
1Staff Engineer1
1VP Engineering1
2Account Executive2
2Head of Sales1
2Sales Associate1

Common mistakes

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.

Related SQL tutorials