Reading history

SQL Self Join

5 min read 0 views

Learn how to join a table to itself with aliases, show each employee with their manager, find pairs of rows without duplicates, and compare related rows.

Sometimes the rows you want to connect live in the same table. Each employee row stores a manager_id, and the manager is just another employee in that table. Two students in the same city are two rows of the same students table. To compare or connect rows like these, you join a table to itself. This is called a self join.

In this lesson you will learn

  • Why a self join needs two table aliases
  • How to show each employee with their manager
  • Why LEFT JOIN keeps the person at the top
  • How to find pairs of rows without duplicates
  • How to compare a row with a related row

You should know SQL joins.

One Table, Two Roles

SQL has no special keyword for a self join. You write an ordinary join, but list the same table twice with two different aliases. Each alias plays a different role. Below, e is the employee and m is the manager.

employees AS e (employee)idnamemanager_id1ShahanaNULL2Faisal14Rubel27Sumi4employees AS m (manager)idnamemanager_id1ShahanaNULL2Faisal14Rubel27Sumi4m.id = e.manager_idSame table, two aliases: row “Rubel” (e) links to row “Faisal” (m)
-- Each employee with the name of their manager
SELECT e.name  AS employee,
       e.title,
       m.name  AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.id = e.manager_id
ORDER BY e.id;

Output

+----------+------------+---------+
| employee | title      | manager |
+----------+------------+---------+
| Shahana  | CEO        | NULL    |
| Faisal   | CTO        | Shahana |
| Lipi     | CFO        | Shahana |
| Rubel    | Engineer   | Faisal  |
| Mou      | Engineer   | Faisal  |
| Anik     | Accountant | Lipi    |
| Sumi     | Intern     | Rubel   |
+----------+------------+---------+
(7 rows)
  • The join condition m.id = e.manager_id says: the manager row is the one whose id equals this employee’s manager_id.
  • Shahana is the CEO, so her manager_id is NULL. LEFT JOIN keeps her with a NULL manager. An inner JOIN would drop her.
  • Without aliases, SQL could not tell which copy of employees a column belongs to.

Finding Pairs

-- Pairs of students who live in the same city
SELECT a.name AS student_1,
       b.name AS student_2,
       a.city
FROM students AS a
JOIN students AS b
  ON  a.city = b.city
  AND a.id   < b.id          -- each pair once, never a student with themselves
ORDER BY a.city, a.name;

-- Employees who earn at least half of their manager's salary
SELECT e.name, e.salary, m.name AS manager, m.salary AS manager_salary
FROM employees AS e
JOIN employees AS m ON m.id = e.manager_id
WHERE e.salary * 2 >= m.salary
ORDER BY e.salary DESC;

Output

+-----------+-----------+------------+
| student_1 | student_2 | city       |
+-----------+-----------+------------+
| Arif      | Nadia     | Chattogram |
| Nusrat    | Rafi      | Dhaka      |
| Nusrat    | Tania     | Dhaka      |
| Tania     | Rafi      | Dhaka      |
+-----------+-----------+------------+
(4 rows)

+--------+--------+---------+----------------+
| name   | salary | manager | manager_salary |
+--------+--------+---------+----------------+
| Faisal | 180000 | Shahana | 250000         |
| Lipi   | 170000 | Shahana | 250000         |
| Mou    | 95000  | Faisal  | 180000         |
| Rubel  | 90000  | Faisal  | 180000         |
+--------+--------+---------+----------------+
(4 rows)
  • a.city = b.city matches students in the same city.
  • a.id < b.id does two jobs. It stops a student pairing with themselves, and it lists each pair once. With <> instead, you would get both Nusrat–Tania and Tania–Nusrat.
  • The second query compares each employee’s salary with their manager’s salary, which sit in two different rows.

Common Uses

QuestionJoin condition
Who is each person’s manager?m.id = e.manager_id
Which customers live in the same area?a.area = b.area AND a.id < b.id
Which bookings overlap?a.room = b.room AND a.start < b.finish AND b.start < a.finish
Which products cost more than another in the same category?a.category = b.category AND a.price > b.price

For a chain of many levels, such as the whole management tree, use a recursive query instead of joining the table again and again. To compare a row with the row just before it in time, LAG and LEAD are usually simpler.

Common Mistakes

  1. Forgetting the aliases. employees JOIN employees is ambiguous; give each copy a name.
  2. Using <> for pairs. Every pair appears twice. Use <.
  3. Using an inner join for a hierarchy. The top person, with no manager, disappears.
  4. Mixing up the direction. e.id = m.manager_id gives each manager’s reports, not each employee’s manager.

Practice Exercises

Exercise 1. List each manager with the number of people who report directly to them.

Show answer
SELECT m.name AS manager, COUNT(*) AS direct_reports
FROM employees AS e
JOIN employees AS m ON m.id = e.manager_id
GROUP BY m.id
ORDER BY direct_reports DESC;

Shahana and Faisal have 2 each; Lipi and Rubel have 1.

Exercise 2. Find pairs of students in the same department where the first has a higher CGPA than the second.

Show answer
SELECT a.name AS higher, b.name AS lower, a.dept
FROM students AS a
JOIN students AS b ON a.dept = b.dept AND a.cgpa > b.cgpa;

Rows with a NULL CGPA never match, because comparisons with NULL are unknown.

Frequently Asked Questions

What is a self join in SQL?

A self join joins a table to itself. You list the same table twice with different aliases, such as e for employee and m for manager, and join them on a condition that links two rows of that table.

How do I avoid duplicate pairs in a self join?

Add a condition such as a.id < b.id. It removes a row being paired with itself and keeps only one order of each pair, so A with B appears but B with A does not.

Summary

  • A self join lists one table twice with two aliases, each playing a different role.
  • Use LEFT JOIN for hierarchies so the top row is kept.
  • Use a.id < b.id to get each pair once.
  • For deep hierarchies use recursive queries; for “previous row” use LAG.

Next: SQL CROSS JOIN and Calendar Tables.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *