Real databases never live in a single table. Customers in one table, orders in another, products in a third. Joins are how you stitch them back together for analysis.
Why we join
Take two tables: customers(id, name) and orders(id, customer_id, amount). To answer "which customers placed which orders", you need to connect them on the matching key — that's a join.
INNER JOIN
Returns rows with a match in both tables.
SELECT c.name, o.amount, o.order_dateFROM customers cINNER JOIN orders oON o.customer_id = c.id;
LEFT JOIN
Returns all rows from the left table plus matches from the right. Where there's no match, the right side is NULL.
-- All customers, including those who never orderedSELECT c.name, o.amountFROM customers cLEFT JOIN orders oON o.customer_id = c.id;
RIGHT & FULL OUTER JOIN
-- RIGHT — mirror image of LEFT (rarely used; flip the tables instead)SELECT c.name, o.amountFROM customers cRIGHT JOIN orders o ON o.customer_id = c.id;-- FULL OUTER — every row from BOTH tablesSELECT c.name, o.amountFROM customers cFULL OUTER JOIN orders o ON o.customer_id = c.id;
| Join | Returns |
|---|---|
| INNER | rows that match in BOTH tables |
| LEFT | all rows from LEFT + matches from right |
| RIGHT | all rows from RIGHT + matches from left |
| FULL OUTER | all rows from both, NULL where no match |
Finding missing matches
The classic interview pattern — "find customers who never placed an order":
SELECT c.id, c.nameFROM customers cLEFT JOIN orders o ON o.customer_id = c.idWHERE o.id IS NULL;
This is faster than the equivalent NOT IN on most engines, and unlike NOT IN it handles NULLs correctly.
Self joins
A self join is when you join a table to itself — for example, an employees table where each row has a manager_id:
-- Get every employee with their manager's nameSELECT e.name AS employee, m.name AS managerFROM employees eLEFT JOIN employees mON m.id = e.manager_id;
Key takeaways
- 01INNER JOIN keeps only matched rows. LEFT JOIN keeps all left rows + matches.
- 02Always alias your tables (c, o, e, m) — it makes joins readable.
- 03LEFT JOIN ... WHERE x IS NULL is the canonical "find rows in A but not B" pattern.
- 04RIGHT JOIN exists but is rarely written — just flip the tables and use LEFT.
- 05Self joins solve hierarchy problems (employees → managers, comments → parent comments).
