Self Join joins a table with itself (e.g., employees/managers).
UNION
Combines results from two SELECTs. UNION ALL keeps duplicates.
Self Join joins a table with itself (e.g., employees/managers).
Combines results from two SELECTs. UNION ALL keeps duplicates.
SELECT e.name, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id; SELECT name, email FROM customers UNION SELECT name, email FROM vendors;
-- Self join: employees and managers SELECT e.name AS employee, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id; -- UNION removes duplicates SELECT name FROM customers UNION SELECT name FROM suppliers ORDER BY name; -- UNION ALL keeps duplicates SELECT city FROM customers UNION ALL SELECT city FROM suppliers; -- UNION with different tables SELECT id, "order" AS src FROM orders UNION SELECT id, "refund" AS src FROM refunds;
Find employees with no manager.
SELECT e.name FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id
WHERE m.id IS NULL;
UNION vs UNION ALL?
UNION removes duplicates; UNION ALL keeps all rows.
Hierarchical data (org charts), comparing rows (sequential data), finding relationships within the same table.