Introduction
We use self join to connect rows in the same table that have a parent-child relationship. This helps us see how items are linked in a hierarchy.
Jump into concepts and practice - no test required
We use self join to connect rows in the same table that have a parent-child relationship. This helps us see how items are linked in a hierarchy.
SELECT child.column, parent.column FROM table AS child JOIN table AS parent ON child.parent_id = parent.id;
SELECT e.name AS employee, m.name AS manager FROM employees AS e JOIN employees AS m ON e.manager_id = m.id;
SELECT c.name AS category, p.name AS parent_category FROM categories AS c JOIN categories AS p ON c.parent_id = p.id;
This creates a simple employee table with managers, then shows each employee with their manager's name. If an employee has no manager, it shows NULL.
CREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(50), manager_id INT ); INSERT INTO employees (id, name, manager_id) VALUES (1, 'Alice', NULL), (2, 'Bob', 1), (3, 'Charlie', 1), (4, 'David', 2); SELECT e.name AS employee, m.name AS manager FROM employees AS e LEFT JOIN employees AS m ON e.manager_id = m.id ORDER BY e.id;
Use LEFT JOIN if some rows might not have a parent (like top-level items).
Self joins can be used multiple times to go up several levels in a hierarchy.
Self join connects rows in the same table to show parent-child links.
Use table aliases to keep the query clear.
It helps display hierarchical data like managers, categories, or parts.
self join in SQL when working with hierarchical data?employees table with columns id, name, and manager_id?employees table to itself using aliases (e and m) and match e.manager_id = m.id to get the manager's name.categories table:id | name | parent_id ---+------------+---------- 1 | Electronics| NULL 2 | Computers | 1 3 | Laptops | 2 4 | Phones | 1 5 | Smartphones| 4
SELECT c.name AS category, p.name AS parent_category FROM categories c LEFT JOIN categories p ON c.parent_id = p.id ORDER BY c.id;
c.parent_id = p.id. If no parent, parent_category is NULL.SELECT e.name, m.name AS manager_name FROM employees e JOIN employees m ON e.id = m.manager_id;
e.id = m.manager_id, which means employee id equals manager's manager_id, which is incorrect.e.manager_id = m.id so employee's manager_id matches manager's id.parts table with columns part_id, part_name, and parent_part_id. Write a query to list each part with its top-level ancestor part name (the root parent with parent_part_id IS NULL). Which approach correctly achieves this using self joins?