CleverSphere

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. 1 · JOIN
  2. 2
  3. 3

For each grade entry give the name and the grade.

students

idnamemajorsemestercity
1MaxLaw5Berlin
2ClaraLaw1Basel
3EvaLaw6Basel
4JonasBusiness6Zürich
5AnnaLaw8Zürich
6GretaLaw1Berlin
7DavidLaw3Zürich

grades

student_idcourse_idgrade
721.3
243
442.7
122.3
314
211.7
321.7
223
422.3
713.3
+ More tables: courses

courses

idtitlecreditslecturer
1Calculus6Meier
2Marketing3Huber
3Databases5Weber
4Law5Meier

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

idnamemajorsemestercity
1JonasLaw1Berlin
2NoraLaw7Berlin
3GretaChemistry1Zürich
4BenComputing8Bern
5DavidLaw8Zürich
6FelixChemistry5Wien
7ClaraComputing8Basel

courses

idtitlecreditslecturer
1Marketing5Huber
2Law5Huber
3Statistics6Weber
4Calculus6Keller

grades

student_idcourse_idgrade
733.7
342.3
512.3
621.7
113.7
232
312
532.3
642.7
323.3
133
142.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.

Related

More topics