Skip to content

Self joins

Join a table to itself to compare rows with each other, such as employees with managers or events with later events.

Practise: 9 questions

When you need it

"Employees who earn more than their manager", "pairs of users from the same country", "orders placed within an hour of each other", "who reports to whom". Words that signal it: "than their manager", "pairs", "both", "another row with the same", "compare each with".

The table holds both sides of the comparison. You give it two aliases and join it to itself.

The shape of the query

select a.col, b.col
from t a
join t b
  on b.key = a.other_key      -- how the two copies relate
 and a.id <> b.id             -- do not match a row with itself
where <condition comparing a and b>;

Step by step:

  1. Name the two roles: "employee" and "manager", or "first order" and "later order".
  2. Join on the link between them. For a hierarchy the link is manager_id = employee_id.
  3. For pairs, stop duplicates with a.id < b.id, which counts each pair once and never a row with itself.
  4. Filter on the comparison.
select e.full_name as employee,
       m.full_name as manager,
       e.salary as employee_salary,
       m.salary as manager_salary
from employees e
join employees m on m.employee_id = e.manager_id
where e.salary > m.salary
order by e.salary - m.salary desc, e.employee_id;

The inner join drops the CEO because there is no manager row. To list everyone with their manager and keep the CEO, switch to left join.

Pairs from one table, each counted once:

select a.customer_id as customer_a,
       b.customer_id as customer_b,
       a.country
from customers a
join customers b
  on b.country = a.country
 and a.customer_id < b.customer_id
where a.referral_source = 'referral'
  and b.referral_source = 'referral'
order by a.country, a.customer_id, b.customer_id
limit 10;

Traps interviewers look for

Variations

In other warehouses

Practise self joins