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:
- Name the two roles: "employee" and "manager", or "first order" and "later order".
- Join on the link between them. For a hierarchy the link is
manager_id = employee_id. - For pairs, stop duplicates with
a.id < b.id, which counts each pair once and never a row with itself. - 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
- Matching a row with itself. Without
a.id <> b.id(or<), every row pairs with itself. - Duplicate pairs.
(A, B)and(B, A)are the same pair. Use<to keep one. - Losing the top of the tree. The CEO has a NULL
manager_id. An inner join drops them. Use a left join if "everyone" is the ask. - Row explosion. A self join on a column with many repeats creates a quadratic number of rows. Joining 1000 rows on a column with 10 values gives about 100,000 pairs. Filter early.
- Ambiguous column names. Both copies have the same columns. Prefix every column with its alias.
- Using a self join when a window is clearer. "Previous order for the same customer" is
lag(), not a self join onorder_id - 1. Ids are not guaranteed to be consecutive.
Variations
- Hierarchy depth. One self join gives manager. Two give the manager's manager. For unknown depth use a recursive CTE.
- Time-based pairs. Join where
b.ts > a.ts and b.ts <= a.ts + interval '1 hour'to find events close together. - Same-group comparisons. "Employees who earn more than the department average" can use a join to an aggregate instead.
- Consecutive rows. Join on a rank offset (
b.rn = a.rn + 1) when you cannot useLAG. - Co-occurrence. Pairs of products bought in the same order come from
order_itemsjoined to itself onorder_id.
In other warehouses
- Self joins are written the same way in Snowflake, BigQuery, SQL Server, MySQL and Redshift.
- Recursive hierarchies: PostgreSQL, MySQL, Snowflake and BigQuery write
with recursive. SQL Server writeswithand has norecursivekeyword. - Snowflake also has
CONNECT BYfor hierarchies. A recursive CTE is the portable choice.