Introduction
A self join helps you compare rows in the same table by joining the table to itself.
Jump into concepts and practice - no test required
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.price = p2.price WHERE p1.id <> p2.id;
CREATE TABLE employees ( id INT, name VARCHAR(50), manager_id INT ); INSERT INTO employees VALUES (1, 'Alice', NULL), (2, 'Bob', 1), (3, 'Charlie', 1), (4, '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 SQL?employees with alias e1 and e2?e1 and e2 to distinguish the two instances.e1.id = e2.manager_id to find employees and their managers.employees with columns id, name, and manager_id, what will this query return?SELECT e1.name AS Employee, e2.name AS Manager FROM employees e1 LEFT JOIN employees e2 ON e1.manager_id = e2.id;
SELECT e1.name, e2.name FROM employees e1 JOIN employees e2 ON e1.id = e2.id;
e1.id = e2.id, which matches each row to itself only, not to related rows.employees with columns id, name, and manager_id. Write a query using self join to find all employees who share the same manager. Which query correctly achieves this?manager_id values must be equal but employees must be different.e1.manager_id = e2.manager_id finds employees with the same manager. Adding WHERE e1.id <> e2.id excludes pairing an employee with themselves.