Introduction
A Self JOIN lets you compare rows in the same table to find related 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 WHERE p1.id <> p2.id;
CREATE TABLE employees ( id INT PRIMARY KEY, 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 aliases e1 and e2 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.manager_id WHERE e1.manager_id = NULL;
= NULL is incorrect; SQL requires IS NULL to check NULL values.employees with columns id, name, and manager_id. Write a query using SELF JOIN to find all employees who are also managers of others. Which query correctly returns the names of employees who manage at least one other employee?Pass the test and this pattern moves unknown