What are the different types of SQL JOINs? Explain with examples
SQL JOINs combine rows from two or more tables based on a related column. INNER JOIN returns only matching rows from both tables — the intersection. LEFT JOIN returns all rows from the left table and matching rows from the right; unmatched right rows show NULL. RIGHT JOIN is the mirror: all right rows, matching left. FULL OUTER JOIN returns all rows from both tables, with NULLs where no match exists. CROSS JOIN produces the Cartesian product — every row from table A paired with every row from table B. SELF JOIN is joining a table to itself, useful for hierarchical data like employees and their managers.
In practice, INNER JOIN is most common for combining related data. LEFT JOIN is essential when you need to preserve all records from the primary table (e.g., all customers including those with no orders). FULL OUTER reveals gaps — rows that exist in one table but not the other. CROSS JOIN is rarely used in production but appears in interview puzzles. SELF JOIN solves "find employees earning more than their manager" by aliasing the same table twice.
-- Schema: employees(id, name, manager_id, salary), departments(id, name)
-- INNER JOIN: only employees with a department
SELECT e.name, d.name AS dept
FROM employees e
INNER JOIN departments d ON e.dept_id = d.id;
-- LEFT JOIN: all employees, NULL if no department
SELECT e.name, d.name AS dept
FROM employees e
LEFT JOIN departments d ON e.dept_id = d.id;
-- FULL OUTER: all from both, NULLs where no match
SELECT e.name, d.name AS dept
FROM employees e
FULL OUTER JOIN departments d ON e.dept_id = d.id;
-- CROSS JOIN: every employee with every department
SELECT e.name, d.name FROM employees e CROSS JOIN departments d;
-- SELF JOIN: employee and their manager
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;
Key Takeaways
- INNER = intersection; LEFT/RIGHT = preserve one side; FULL = union with NULLs; CROSS = Cartesian product
- SELF JOIN uses table aliases to treat the same table as two different entities
- Always specify JOIN condition — forgetting it with multiple tables can accidentally create CROSS JOIN