SQL aggregate functions
Aggregate functions combine many rows into one value.
Rules
- COUNT(*) counts rows
- COUNT(column) skips NULL
- SUM, AVG, MIN, MAX
Your turn
Three problems on this topic. You can run the query first.
- 1 · Aggregate functions
- 2
- 3
How many students are there?
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Max | Chemistry | 7 | Berlin |
| 2 | Lena | Business | 4 | Zürich |
| 3 | Nora | Business | 2 | Wien |
| 4 | Anna | Law | 7 | Basel |
| 5 | Eva | Law | 6 | Wien |
| 6 | David | Chemistry | 5 | Zürich |
| 7 | Clara | Business | 2 | Berlin |
+ − More tables: courses, grades
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Law | 5 | Weber |
| 2 | Marketing | 6 | Keller |
| 3 | Databases | 5 | Huber |
| 4 | Calculus | 4 | Weber |
grades
| student_id | course_id | grade |
|---|---|---|
| 7 | 3 | 1.3 |
| 1 | 4 | 3 |
| 4 | 2 | 2.7 |
| 4 | 3 | 1.7 |
| 2 | 3 | 3.7 |
| 3 | 4 | 1 |
| 1 | 3 | 2.7 |
| 6 | 1 | 1.7 |
| 3 | 2 | 2 |
| 5 | 3 | 1.7 |
| 2 | 2 | 2.3 |
SQL
Any equivalent query counts. It is also checked on data you can’t see.
Worked example
How many students are there?
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Felix | Business | 7 | Berlin |
| 2 | David | Business | 8 | Zürich |
| 3 | Nora | Business | 7 | Zürich |
| 4 | Anna | Computing | 5 | Berlin |
| 5 | Max | Chemistry | 6 | Berlin |
| 6 | Greta | Business | 5 | Wien |
| 7 | Eva | Business | 3 | Basel |
+ − More tables: courses, grades
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Calculus | 5 | Meier |
| 2 | Databases | 3 | Keller |
| 3 | Law | 6 | Meier |
| 4 | Statistics | 4 | Huber |
grades
| student_id | course_id | grade |
|---|---|---|
| 2 | 3 | 3.7 |
| 3 | 1 | 1.3 |
| 6 | 1 | 2 |
| 7 | 4 | 1 |
| 4 | 4 | 1.3 |
| 5 | 2 | 3.3 |
| 3 | 4 | 1.7 |
| 2 | 2 | 2 |
| 5 | 4 | 3.7 |
| 4 | 2 | 2 |
| 7 | 2 | 1.7 |
Worked solution
SELECT COUNT(*) FROM students
Result on the sample data:
count
7
Typical mistake: COUNT(*) counts rows.
Common questions
Does COUNT count NULL?
COUNT(*) does, COUNT(column) does not.
