SQL: GROUP BY
GROUP BY forms groups of equal values. Aggregates are then worked out per group.
Rules
- Every non-aggregated column goes in GROUP BY
- One result row per group
Your turn
Three problems on this topic. You can run the query first.
- 1 · GROUP BY
- 2
- 3
How many students are there per city? Give the city and the count.
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Greta | Chemistry | 7 | Basel |
| 2 | Max | Law | 2 | Bern |
| 3 | Ben | Business | 6 | Zürich |
| 4 | Eva | Business | 7 | Wien |
| 5 | Jonas | Business | 7 | Wien |
| 6 | Anna | Chemistry | 7 | Berlin |
| 7 | Hannah | Chemistry | 2 | Zürich |
+ − More tables: courses, grades
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Statistics | 5 | Meier |
| 2 | Marketing | 6 | Huber |
| 3 | Databases | 4 | Keller |
| 4 | Calculus | 3 | Meier |
grades
| student_id | course_id | grade |
|---|---|---|
| 7 | 3 | 3.7 |
| 2 | 3 | 3.7 |
| 2 | 2 | 3.3 |
| 1 | 1 | 2.7 |
| 1 | 4 | 1.3 |
| 7 | 4 | 1.7 |
| 5 | 2 | 1.7 |
| 4 | 4 | 1.3 |
| 1 | 3 | 1.7 |
| 5 | 4 | 1 |
| 2 | 4 | 3.7 |
| 4 | 3 | 3.3 |
| 3 | 3 | 1.3 |
SQL
Any equivalent query counts. It is also checked on data you can’t see.
Worked example
What is the average semester per major? Give the major and the average.
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Lena | Business | 1 | Wien |
| 2 | Ben | Computing | 2 | Berlin |
| 3 | Hannah | Computing | 1 | Bern |
| 4 | Felix | Law | 8 | Wien |
| 5 | Clara | Chemistry | 8 | Berlin |
| 6 | David | Business | 2 | Wien |
| 7 | Eva | Computing | 2 | Bern |
+ − More tables: courses, grades
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Law | 3 | Huber |
| 2 | Calculus | 5 | Huber |
| 3 | Statistics | 6 | Weber |
| 4 | Marketing | 3 | Keller |
grades
| student_id | course_id | grade |
|---|---|---|
| 7 | 1 | 2 |
| 5 | 4 | 3.3 |
| 6 | 3 | 2 |
| 3 | 2 | 3 |
| 1 | 4 | 3.3 |
| 6 | 2 | 1.7 |
| 3 | 1 | 2.3 |
| 1 | 1 | 2 |
| 3 | 3 | 3.7 |
| 5 | 2 | 1.7 |
| 2 | 1 | 1.7 |
Worked solution
SELECT major, AVG(semester) FROM students GROUP BY major
Result on the sample data:
major | avg
Business | 1.5
Computing | 1.666667
Law | 8
Chemistry | 8
Typical mistake: GROUP BY makes one row per group.
Common questions
Why do I get a “not in GROUP BY” error?
Because a non-aggregated column would be ambiguous.
