What are the different SQL joins? Explain with an example.
A join combines rows from two tables using a related column, usually a foreign key.
The main joins
- INNER JOIN: only rows that match in both tables.
- LEFT (OUTER) JOIN: every row from the left table, with matching right rows or
NULLs when there is no match. Use it for "customers and their orders, including customers with none". - RIGHT (OUTER) JOIN: the mirror image; most teams rewrite it as a LEFT JOIN for readability.
- FULL (OUTER) JOIN: all rows from both sides,
NULLs where either side is missing. MySQL has no FULL JOIN; emulate it withLEFT JOIN ... UNION ... RIGHT JOIN. - CROSS JOIN: every combination (a Cartesian product): useful for generating calendars or test grids, dangerous by accident.
- SELF JOIN: a table joined to itself with aliases, for hierarchies such as employee → manager.
Classic pitfalls
- A filter on the right table in
WHEREturns a LEFT JOIN into an INNER JOIN (WHERE o.status = 'PAID'removes customers with no orders). Put such conditions in theONclause instead. - Joining two one-to-many relationships at once multiplies rows (fan-out), so
SUMvalues are inflated. Aggregate in a subquery first.
Example
sql
-- customers(id, name), orders(id, customer_id, amount, status)
-- Customers with their number of paid orders, including customers with none
SELECT c.name, COUNT(o.id) AS paid_orders
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.id
AND o.status = 'PAID' -- in ON, so customers without orders stay
GROUP BY c.id, c.name
ORDER BY paid_orders DESC;
-- Employees with their manager's name (self join)
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;
-- Anti-join: customers who never ordered
SELECT c.*
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);Follow-up questions interviewers ask
Try answering each one before you open it.
Why prefer NOT EXISTS over NOT IN?
If the subquery returns a single NULL, x NOT IN (subquery) is never true (comparisons with NULL are unknown), so the query silently returns no rows. NOT EXISTS is not affected by NULLs and most optimisers turn it into an efficient anti-join.