Skip to main content
Albero Academy

Advanced Joins & Set Operations

Join a table to itself, chain many tables, find non-matches, and combine result sets with UNION.

Chapter 5MySQL15 min readBeginner friendly
  • #MySQL
  • #Joins
  • #UNION

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:

employee → manager
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT 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:

three tables
SELECT s.name, p.name AS programme, b.city AS batch_city
FROM students s
JOIN programmes p ON s.programme_id = p.id
JOIN batches b ON s.batch_id = b.id
WHERE 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:

who has no match?
SELECT s.name
FROM students s
LEFT JOIN enrolments e ON s.id = e.student_id
WHERE 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:

stacking results
SELECT name, 'student' AS role FROM students
UNION -- removes duplicate rows
SELECT name, 'mentor' AS role FROM mentors;
-- UNION ALL keeps duplicates and is faster (no de-dup pass)
SELECT city FROM students
UNION ALL
SELECT 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

  1. 01A self-join joins a table to itself with two aliases — ideal for hierarchies (employee/manager).
  2. 02Chain a JOIN … ON per table to combine data spread across many tables.
  3. 03Anti-join = LEFT JOIN + WHERE right-key IS NULL to find rows with no match.
  4. 04JOIN combines columns sideways; UNION stacks result sets vertically (same columns required).
  5. 05Prefer UNION ALL unless you need duplicates removed — plain UNION adds a de-dup pass.