TExcelTAD
Home › SQL › SQL Self Join

SQL Self Join

A self join joins a table with itself. There is no special keyword — you write an ordinary join and list the same table twice under different aliases, so the database treats them as two copies.

sql
SELECT a.column, b.column
FROM table_name AS a
JOIN table_name AS b ON condition;

Self joins are natural whenever rows in a table refer to other rows in the same table, or when you want to compare rows with each other.

Employees and their managers

In employees, manager_id holds the employee_id of the person's boss. Join employees (as e, the employee) to employees (as m, the manager):

sql · try it yourself
SELECT e.first_name || ' ' || e.last_name AS employee,
       e.title,
       m.first_name || ' ' || m.last_name AS manager
FROM employees AS e
JOIN employees AS m ON m.employee_id = e.manager_id
ORDER BY manager, employee;
employee      | title              | manager
--------------+--------------------+------------
Elena Popescu | Data Analyst       | Grace Holt
Lin Zhou      | Operations Manager | Grace Holt
Victor Ames   | Sales Manager      | Grace Holt
Hana Sato     | Support Specialist | Lin Zhou
Marco Ricci   | Warehouse Lead     | Lin Zhou
Aisha Bello   | Sales Rep          | Victor Ames
Owen Price    | Sales Rep          | Victor Ames
Rosa Delgado  | Sales Rep          | Victor Ames
Tom Becker    | Sales Rep          | Victor Ames
(9 rows)

Grace Holt, the CEO, is missing: she has no manager, so the inner join finds no partner for her. Use a LEFT JOIN to keep her:

sql · try it yourself
SELECT e.first_name AS employee,
       COALESCE(m.first_name, '(nobody)') AS reports_to
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id
WHERE e.employee_id <= 4
ORDER BY e.employee_id;
employee | reports_to
---------+-----------
Grace    | (nobody)
Victor   | Grace
Lin      | Grace
Rosa     | Victor
(4 rows)

Counting direct reports

Turn it around: for each manager, how many people report to them, and do they earn more than their team on average?

sql · try it yourself
SELECT m.first_name AS manager,
       m.salary,
       COUNT(e.employee_id) AS reports,
       ROUND(AVG(e.salary)) AS team_avg_salary
FROM employees AS m
JOIN employees AS e ON e.manager_id = m.employee_id
GROUP BY m.employee_id
ORDER BY reports DESC;
manager | salary | reports | team_avg_salary
--------+--------+---------+----------------
Victor  | 98000  | 4       | 58875
Grace   | 185000 | 3       | 88333
Lin     | 95000  | 2       | 52500
(3 rows)

Comparing rows of the same table

A self join can also pair rows that share some property. Which customers live in the same city as another customer?

sql · try it yourself
SELECT a.city, a.name AS customer_1, b.name AS customer_2
FROM customers AS a
JOIN customers AS b
  ON b.city = a.city
 AND b.customer_id > a.customer_id
ORDER BY a.city;
city    | customer_1      | customer_2
--------+-----------------+---------------
Berlin  | Corner Cafe     | Priya Kowalski
London  | Nonna's Kitchen | Jonas Garcia
Paris   | Bright Bytes    | Kai Moreau
Toronto | Green Fork      | Elif Yilmaz
(4 rows)

The condition b.customer_id > a.customer_id does two jobs: it stops a customer from being paired with themselves, and it keeps only one of the two mirrored pairs (A–B, not also B–A).

Products cheaper than another in the same category

sql · try it yourself
SELECT cheap.name AS product, cheap.price, COUNT(*) AS pricier_in_category
FROM products AS cheap
JOIN products AS other
  ON other.category_id = cheap.category_id
 AND other.price > cheap.price
WHERE cheap.category_id = 2
GROUP BY cheap.product_id
ORDER BY cheap.price;
product          | price | pricier_in_category
-----------------+-------+--------------------
Bagels           | 4.9   | 3
Sourdough Loaf   | 5.5   | 2
Butter Croissant | 6.25  | 1
(3 rows)

The most expensive bakery item is missing because no product beats it. For deeper hierarchies (manager of manager of …), see the recursive CTE lesson.

Test yourself

What is required to join a table with itself?

  1. The SELF JOIN keyword
  2. Two different aliases for the table
  3. A primary key on every column
  4. A view

Why add b.customer_id > a.customer_id when pairing customers in the same city?

  1. To sort the result
  2. To avoid self-pairs and mirrored duplicate pairs
  3. To speed up the query only
  4. It is required syntax