Introduction
A self join lets you compare rows in a table to other rows in the same table. It helps find relationships within the same data.
SELECT a.column1, b.column2 FROM table_name a JOIN table_name b ON a.common_field = b.common_field WHERE condition;
SELECT e1.name AS employee, e2.name AS manager FROM employees e1 JOIN employees e2 ON e1.manager_id = e2.id;
SELECT p1.product_name, p2.product_name FROM products p1 JOIN products p2 ON p1.category = p2.category AND p1.id <> p2.id;
SELECT a.date AS earlier_date, b.date AS later_date FROM dates a JOIN dates b ON a.date < b.date;
CREATE TABLE employees ( id SERIAL PRIMARY KEY, name VARCHAR(50), manager_id INT ); INSERT INTO employees (name, manager_id) VALUES ('Alice', NULL), ('Bob', 1), ('Charlie', 1), ('David', 2); SELECT e1.name AS employee, e2.name AS manager FROM employees e1 LEFT JOIN employees e2 ON e1.manager_id = e2.id ORDER BY e1.id;
self join in PostgreSQL?employees with aliases e1 and e2?employees(id, name, manager_id) with data:id | name | manager_id ---+-------+----------- 1 | Alice | NULL 2 | Bob | 1 3 | Carol | 1 4 | Dave | 2
SELECT e1.name AS employee, e2.name AS manager FROM employees e1 LEFT JOIN employees e2 ON e1.manager_id = e2.id ORDER BY e1.id;
SELECT e1.name, e2.name FROM employees e1 JOIN employees e2 ON e1.manager_id = e2.manager_id WHERE e1.id != e2.id;
Pass the test and this pattern moves unknown