Several tables and the self join
138 min
Many questions need three or four tables, not two. And sometimes a table has to be joined with itself.
Joins in a chain
Each JOIN adds one more table to the result. Student → group → faculty:
Through a link table (M:N) — student, subject and score:
Every JOIN gets its own ON. Build the chain from the schema: each next table must connect to one already in the query.
Self join — a table joined with itself
In the company database an employee’s manager lives in the same employees table (manager_id). To see employees next to their managers, take the table twice under two aliases:
e plays the employee, m plays the manager. Without aliases this query cannot be written.
A calculation across tables
Four tables: order lines → orders → products → categories. Revenue per category from delivered orders:
For every grade, show its score, the student’s first_name and the subject name (subjects.name).
For every employee who has a manager, show their first_name and the manager’s first_name.
For every completed trip, show the driver’s first_name, the car’s model and the fare.
Remember
- Every extra table is another
JOIN … ON …. - Self join: one table, two different aliases.
- Find the “path” in the schema before writing the query.