SQL GROUP BY
What you will learn
- How
GROUP BYmakes one row per group - How aggregates are calculated per group
- How to group by several columns
- How to sort the groups, and the rule for the
SELECTlist
This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.
1. One row per group
Lesson 3.1 summarised the whole table. GROUP BY splits the rows into groups that share a value, and calculates the aggregates once per group:
Orders per status:
SELECT status, COUNT(*) AS orders FROM orders GROUP BY status ORDER BY status;
status orders
--------- ------
cancelled 170
delivered 1878
paid 186
pending 135
shipped 231
(5 rows)
Accounts per type:
SELECT account_type, COUNT(*) AS accounts FROM accounts GROUP BY account_type ORDER BY account_type;
account_type accounts
------------ --------
checking 316
savings 134
(2 rows)
Students per year of enrolment:
SELECT enrolled_year, COUNT(*) AS students FROM students GROUP BY enrolled_year ORDER BY enrolled_year;
enrolled_year students
------------- --------
2023 83
2024 102
2025 86
2026 89
(4 rows)
The result has one row for each different value of the grouping column. The numbers add up to the whole table, which is a good check.
2. Aggregates per group
Any aggregate works per group:
Payments per method: how many, the total and the average:
SELECT method, COUNT(*) AS payments, ROUND(SUM(amount), 2) AS total, ROUND(AVG(amount), 2) AS average
FROM payments GROUP BY method ORDER BY method;
method payments total average
-------- -------- --------- -------
card 1262 126798.77 100.47
cash 246 26346.97 107.1
transfer 471 49583.35 105.27
wallet 316 30599.8 96.83
(4 rows)
Ledger rows per kind: how many and the total amount in cents:
SELECT kind, COUNT(*) AS rows_found, SUM(amount_cents) AS total_cents, MAX(amount_cents) AS largest
FROM transactions GROUP BY kind ORDER BY kind;
kind rows_found total_cents largest
------------ ---------- ----------- -------
deposit 3107 99441800 80000
fee 403 225700 1000
interest 308 72830 876
transfer_in 539 7891800 29700
transfer_out 539 7891800 29700
withdrawal 2519 37089800 30000
(6 rows)
Enrollments per section, with the best and worst grade:
SELECT section_id, COUNT(*) AS enrolled, MIN(grade) AS lowest, MAX(grade) AS highest
FROM enrollments GROUP BY section_id ORDER BY section_id LIMIT 6;
section_id enrolled lowest highest
---------- -------- ------ -------
1 15 50.1 88.6
2 20 47.7 93.0
3 15 41.2 98.6
4 25 53.7 84.3
5 32 39.4 100.0
6 19 51.6 93.4
(6 rows)
3. WHERE before GROUP BY
WHERE still selects the rows before they are grouped:
Payments of 2026 only, per method:
SELECT method, COUNT(*) AS payments, ROUND(SUM(amount), 2) AS total
FROM payments WHERE paid_on >= '2026-01-01' GROUP BY method ORDER BY method;
method payments total
-------- -------- --------
card 573 55837.55
cash 108 12649.37
transfer 224 25810.22
wallet 123 12715.09
(4 rows)
Open accounts only, per type:
SELECT account_type, COUNT(*) AS accounts, SUM(balance_cents) AS total_cents
FROM accounts WHERE status = 'open' GROUP BY account_type ORDER BY account_type;
account_type accounts total_cents
------------ -------- -----------
checking 284 38813900
savings 120 16220959
(2 rows)
Courses of three or more credits, per number of credits:
SELECT credits, COUNT(*) AS courses FROM courses WHERE credits >= 3 GROUP BY credits ORDER BY credits;
credits courses
------- -------
3 7
4 7
(2 rows)
4. Several columns
Group by two columns and you get one row for each combination:
SELECT method, SUBSTR(paid_on, 1, 4) AS year, COUNT(*) AS payments
FROM payments GROUP BY method, SUBSTR(paid_on, 1, 4) ORDER BY method, year LIMIT 8;
method year payments
-------- ---- --------
card 2024 226
card 2025 463
card 2026 573
cash 2024 47
cash 2025 91
cash 2026 108
transfer 2024 82
transfer 2025 165
(8 rows)
SELECT account_type, status, COUNT(*) AS accounts
FROM accounts GROUP BY account_type, status ORDER BY account_type, status;
account_type status accounts
------------ ------ --------
checking closed 21
checking frozen 11
checking open 284
savings closed 9
savings frozen 5
savings open 120
(6 rows)
SELECT term, COUNT(*) AS sections, SUM(capacity) AS seats
FROM sections GROUP BY term ORDER BY term;
term sections seats
----------- -------- -----
2025-Autumn 14 405
2025-Spring 16 480
2026-Spring 11 325
(3 rows)
5. The rule for the SELECT list
In a grouped query, every column in the SELECT list must be either in the GROUP BY or inside an aggregate function. The grouped columns tell you which group a row is; the aggregates summarise it. A plain column that is neither has no single value for the group.
In other databases. PostgreSQL and MySQL enforce this rule and reject a query that breaks it (lesson 3.1 quotes their documentation). SQLite does not, so a mistake here may not show up as an error. Follow the rule always.
6. Sorting the groups
ORDER BY can sort by the grouping column or by an aggregate, including its alias:
The orders per status, biggest group first:
SELECT status, COUNT(*) AS orders FROM orders GROUP BY status ORDER BY orders DESC, status;
status orders
--------- ------
delivered 1878
shipped 231
paid 186
cancelled 170
pending 135
(5 rows)
The ledger kinds with the most rows first:
SELECT kind, COUNT(*) AS rows_found FROM transactions GROUP BY kind ORDER BY rows_found DESC, kind;
kind rows_found
------------ ----------
deposit 3107
withdrawal 2519
transfer_in 539
transfer_out 539
fee 403
interest 308
(6 rows)
Years of enrolment with the most students first:
SELECT enrolled_year, COUNT(*) AS students FROM students GROUP BY enrolled_year ORDER BY students DESC, enrolled_year;
enrolled_year students
------------- --------
2024 102
2026 89
2025 86
2023 83
(4 rows)
Worked example: from a question to a GROUP BY
"How many customers do we have in each country?"
| Part of the question | Part of the query |
|---|---|
| "in each country" | GROUP BY country (and country in the SELECT) |
| "how many customers" | COUNT(*) |
| "biggest first" | ORDER BY COUNT(*) DESC |
Words like each, per and by in a question usually point to GROUP BY. The result is SELECT country, COUNT(*) FROM customers GROUP BY country ORDER BY COUNT(*) DESC. The table is made up.
Common mistakes
- A plain column in the
SELECTlist that is not grouped. - Forgetting that
NULLs form their own group. - Using
WHEREto filter groups.WHEREfilters rows; lesson 3.3 showsHAVINGfor groups. - Grouping by a column with a different value in almost every row (an id): you get one row per row.
- No
ORDER BY, so the groups come in no promised order.
Key takeaways
GROUP BYmakes one row per group; aggregates are calculated per group.WHEREselects rows before grouping.- Several grouping columns give one row per combination.
- Every
SELECTcolumn is grouped or aggregated. - Sort groups with
ORDER BY, by the key or by an aggregate.
Practice
1. Write a query for the number of customers in each city.
Show answer
SELECT city, COUNT(*) FROM customers GROUP BY city;
2. What do the group counts add up to?
Show answer
The number of rows that were grouped (the whole table, if there is no WHERE).
3. What is wrong with SELECT city, name, COUNT(*) FROM customers GROUP BY city;?
Show answer
name is neither grouped nor aggregated; a city has many names. Group by it too or leave it out.
4. How do you list the groups from the largest to the smallest?
Show answer
ORDER BY COUNT(*) DESC (or the alias of the count).
5. What does GROUP BY a, b return?
Show answer
One row for every different combination of a and b.
6. Which clause filters rows before grouping?
Show answer
WHERE.