Learn with Abdou

Chapter 7 · Concept 4 of 6

The staff chart loses its top row

one table, two roles

Fourteen staff members, each pointing at a supervisor, except the director at the top.

Can you

  • Join a table to itself under two aliases that name roles
  • Keep the row at the top of the chart with a LEFT JOIN
  • Tell a self-join on the wrong key from one on the right key by what the rows say

A table meets itself

Nothing says the two sides of a join must be different tables. The staff table has a supervisor_id that points at another row of staff. Give the table two aliases and it becomes two copies: e for the employee, m for the manager that e.supervisor_id points at. The aliases name roles, not two tables stored twice.

The bridge is ON m.id = e.supervisor_id. Write ON m.id = e.id instead and every person becomes their own supervisor, fourteen rows of nonsense that run without a complaint.

SELECT e.id AS employee_id, e.first_name AS employee, m.first_name AS supervisor
FROM staff e
LEFT JOIN staff m ON m.id = e.supervisor_id
ORDER BY e.id;
Fourteen rows. Marit, at the top, has no supervisor and is still on the chart. Open in the playground

One row of staff has a NULL supervisor_id: the director, at the top of the chart. An INNER JOIN drops her, because NULL matches nothing. If the chart must show every employee, the employee copy goes on the left of a LEFT JOIN and the director keeps her row with a NULL where a supervisor's name would be.

Rule of thumb. In a self-join the aliases are roles. Pair the pointing column with the key it points at, and keep the top row with a LEFT JOIN.

Going deeper (optional, not on the exam)

The same trick answers questions inside one table of facts: who ran the marathon in both 2024 and 2025, and did they get faster? Pair a results row with another results row of the same runner, one alias per year.

The ladder

Six rungs

Start at the first rung even if the idea looks familiar: it is answerable from the reading alone, and the climb is where the difficulty lives. A wrong answer sends you back to the paragraph that teaches it, then to a hint, then to the worked answer.

Learn

  1. Level 1: Watch it answered

    1 exercise · Not yet

    Practise this rung
  2. Level 2: Fill the blank

    1 exercise · Not yet

    Practise this rung

Practise

  1. Level 3: Predict the result

    1 exercise · Not yet

    Practise this rung
  2. Level 4: Write it yourself

    1 exercise · Not yet

    Practise this rung

Master

  1. Level 5: Repair it

    1 exercise · Not yet

    Practise this rung
  2. Level 6: Transfer it

    1 exercise · Not yet

    Practise this rung

Keep practising

The whole bank for this concept, in any order, with the same review, hint and worked answer.

Practice here is evidence for you and your instructor, never a grade. Grades live in Canvas.