SQL: JOIN
A JOIN links tables through primary and foreign keys.
Rules
- JOIN table ON a = b
- Aliases shorten the query
- n tables need n − 1 joins
Your turn
Three problems on this topic. You can run the query first.
- 1 · JOIN
- 2
- 3
For each grade entry give the name and the grade.
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Max | Law | 5 | Berlin |
| 2 | Clara | Law | 1 | Basel |
| 3 | Eva | Law | 6 | Basel |
| 4 | Jonas | Business | 6 | Zürich |
| 5 | Anna | Law | 8 | Zürich |
| 6 | Greta | Law | 1 | Berlin |
| 7 | David | Law | 3 | Zürich |
grades
| student_id | course_id | grade |
|---|---|---|
| 7 | 2 | 1.3 |
| 2 | 4 | 3 |
| 4 | 4 | 2.7 |
| 1 | 2 | 2.3 |
| 3 | 1 | 4 |
| 2 | 1 | 1.7 |
| 3 | 2 | 1.7 |
| 2 | 2 | 3 |
| 4 | 2 | 2.3 |
| 7 | 1 | 3.3 |
+ − More tables: courses
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Calculus | 6 | Meier |
| 2 | Marketing | 3 | Huber |
| 3 | Databases | 5 | Weber |
| 4 | Law | 5 | Meier |
SQL
Any equivalent query counts. It is also checked on data you can’t see.
Worked example
Give the name and course title of all entries with a grade better (smaller) than 2.
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Jonas | Law | 1 | Berlin |
| 2 | Nora | Law | 7 | Berlin |
| 3 | Greta | Chemistry | 1 | Zürich |
| 4 | Ben | Computing | 8 | Bern |
| 5 | David | Law | 8 | Zürich |
| 6 | Felix | Chemistry | 5 | Wien |
| 7 | Clara | Computing | 8 | Basel |
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Marketing | 5 | Huber |
| 2 | Law | 5 | Huber |
| 3 | Statistics | 6 | Weber |
| 4 | Calculus | 6 | Keller |
grades
| student_id | course_id | grade |
|---|---|---|
| 7 | 3 | 3.7 |
| 3 | 4 | 2.3 |
| 5 | 1 | 2.3 |
| 6 | 2 | 1.7 |
| 1 | 1 | 3.7 |
| 2 | 3 | 2 |
| 3 | 1 | 2 |
| 5 | 3 | 2.3 |
| 6 | 4 | 2.7 |
| 3 | 2 | 3.3 |
| 1 | 3 | 3 |
| 1 | 4 | 2.7 |
Worked solution
SELECT s.name, k.title FROM students s JOIN grades n ON s.id = n.student_id JOIN courses k ON k.id = n.course_id WHERE n.grade < 2
Result on the sample data:
name | title
Felix | Law
Typical mistake: Three tables need two joins.
Common questions
What happens without ON?
You get a cross product of all pairs of rows.
