Chapter 3 covered the four basic joins. Real reporting queries go further: a table joined to itself, three or four tables chained together, and questions of the form "which rows have no match". This chapter completes your joining toolkit.
Self-joins
A self-join joins a table to itself, using two aliases. It's how you model hierarchies — an employee and their manager both live in the same table:
SELECT e.name AS employee, m.name AS managerFROM employees eLEFT JOIN employees m ON e.manager_id = m.id;-- LEFT JOIN so the CEO (manager_id IS NULL) still appears.
Joining many tables
Chain joins to pull together data spread across several tables — just add another JOIN … ON for each:
SELECT s.name, p.name AS programme, b.city AS batch_cityFROM students sJOIN programmes p ON s.programme_id = p.idJOIN batches b ON s.batch_id = b.idWHERE b.city = 'Pune';
Anti-joins — finding non-matches
To find rows with no match (students never enrolled in a programme), LEFT JOIN and keep only the NULL side:
SELECT s.nameFROM students sLEFT JOIN enrolments e ON s.id = e.student_idWHERE e.student_id IS NULL; -- kept only the unmatched students
UNION & set operations
JOIN combines columns sideways; UNION stacks result sets vertically. Both queries must have the same columns:
SELECT name, 'student' AS role FROM studentsUNION -- removes duplicate rowsSELECT name, 'mentor' AS role FROM mentors;-- UNION ALL keeps duplicates and is faster (no de-dup pass)SELECT city FROM studentsUNION ALLSELECT city FROM mentors;
Practice
Write a self-join listing each employee with their manager's name. Chain three tables to list students with their programme and batch city. Use a LEFT JOIN … IS NULL anti-join to find programmes with no students, and a UNION to build one combined contact list of students and mentors.
Key takeaways
- 01A self-join joins a table to itself with two aliases — ideal for hierarchies (employee/manager).
- 02Chain a JOIN … ON per table to combine data spread across many tables.
- 03Anti-join = LEFT JOIN + WHERE right-key IS NULL to find rows with no match.
- 04JOIN combines columns sideways; UNION stacks result sets vertically (same columns required).
- 05Prefer UNION ALL unless you need duplicates removed — plain UNION adds a de-dup pass.
