Chains of joins
Real questions often span three or more tables. A school database:
students(id, name)courses(id, title)enrollments(student_id, course_id, grade)links them: each row says "this student takes this course and has this grade".
To print names next to course titles, join twice:
SELECT students.name, courses.title, enrollments.grade FROM enrollments JOIN students ON students.id = enrollments.student_id JOIN courses ON courses.id = enrollments.course_id ORDER BY students.name, courses.title;
Each JOIN adds one table and one ON rule. Read it as a pipeline: start from enrollments, attach the matching student, then attach the matching course. There is no limit; five-table joins are everyday SQL.
Code exercise · sql
Run it. Each enrollment row becomes a readable line: who, which course, what grade.
Quiz
In the three-table join, why does the query start FROM enrollments rather than FROM students?
Code exercise · sql
Your turn. Compute each course's average grade, rounded to 1 decimal, alphabetical by title. You only need two of the three tables.
Code exercise · sql
Your turn. Print the title and grade of every course Ben takes, alphabetical by title. Same three-table join, plus a WHERE on the student's name (lesson 5-3 showed joins compose with WHERE).