Relational databases store each fact once. Customers live in one table, orders in another, and the link between them is a key. That keeps data clean, but it means almost every useful question needs data from more than one table. A JOIN is how SQL puts that data back together.
This article shows what each type of JOIN returns, using two tiny tables, then covers the traps that produce wrong results without any error.
The example tables
customers orders
id | name id | customer_id | total
---+-------- ----+-------------+------
1 | Amina 101 | 1 | 2500
2 | Karim 102 | 1 | 1200
3 | Sara 103 | 2 | 800
104 | 9 | 400
Notice two things. Sara (id 3) has no orders. Order 104 points to customer 9, who does not exist (perhaps a deleted account, or data imported without a foreign key).
How a JOIN thinks
Conceptually, a JOIN pairs every row of the left table with every row of the right table, then keeps the pairs that satisfy the ON condition. The type of join then decides what to do with rows that found no partner. Databases do not literally build every pair; they use smarter algorithms. But this mental model always gives the right answer.
INNER JOIN: only the matches
SELECT c.name, o.id AS order_id, o.total
FROM customers c
INNER JOIN orders o ON o.customer_id = c.id;
| name | order_id | total |
|---|---|---|
| Amina | 101 | 2500 |
| Amina | 102 | 1200 |
| Karim | 103 | 800 |
Only pairs that match. Sara disappears because she has no orders. Order 104 disappears because it has no customer. Amina appears twice because she has two orders: a join produces one row per matching pair, not one row per customer. JOIN on its own means INNER JOIN.
LEFT JOIN: everything from the left
SELECT c.name, o.id AS order_id, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id;
| name | order_id | total |
|---|---|---|
| Amina | 101 | 2500 |
| Amina | 102 | 1200 |
| Karim | 103 | 800 |
| Sara | NULL | NULL |
Every customer is kept. Where there is no match, the columns from the right table are filled with NULL. This is the join you want for "all customers, with their orders if they have any".
It also gives a classic pattern, the anti-join: find rows with no match.
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL; -- Sara: customers who never ordered
NOT EXISTS expresses the same thing and is often clearer.
RIGHT JOIN: everything from the right
RIGHT JOIN is the mirror image: keep every row of the right table.
SELECT c.name, o.id AS order_id
FROM customers c
RIGHT JOIN orders o ON o.customer_id = c.id;
| name | order_id |
|---|---|
| Amina | 101 |
| Amina | 102 |
| Karim | 103 |
| NULL | 104 |
Order 104 is kept with a NULL customer. Any RIGHT JOIN can be written as a LEFT JOIN by swapping the table order, and most teams do exactly that, because queries read more easily when the "main" table comes first.
FULL OUTER JOIN: everything from both
SELECT c.name, o.id AS order_id
FROM customers c
FULL OUTER JOIN orders o ON o.customer_id = c.id;
| name | order_id |
|---|---|
| Amina | 101 |
| Amina | 102 |
| Karim | 103 |
| Sara | NULL |
| NULL | 104 |
Matches, plus unmatched rows from both sides. It is handy for reconciliation: comparing two lists and seeing what is missing on each side. PostgreSQL, SQL Server and Oracle support it; MySQL does not, and you emulate it with a LEFT JOIN combined with a UNION of the unmatched right rows.
CROSS JOIN and self joins
CROSS JOIN has no condition: every row paired with every row. Three customers and four orders give twelve rows. It is useful for generating combinations (every size with every colour), and dangerous by accident.
A self join joins a table to itself with two aliases, for example employees and their managers stored in the same table:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id;
How the database actually runs a join
The planner picks a physical algorithm based on table sizes and indexes:
- Nested loop: for each row on one side, look up matches on the other, ideally through an index. Great when one side is small.
- Hash join: build a hash table on the smaller side's join key, then scan the other side and probe it. Good for large unsorted inputs with an equality condition.
- Merge join: sort both sides on the key (or read them in order from an index) and walk them together.
You write the logical join; the database picks the physical one. EXPLAIN shows which one it chose. An index on the foreign key column (orders.customer_id here) often makes the difference between a fast nested loop and scanning a large table.
The traps
Filtering the right table in WHERE turns a LEFT JOIN into an INNER JOIN.
-- Wrong: Sara disappears, because o.total is NULL for her
SELECT c.name, o.total FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.total > 1000;
-- Right: the condition belongs to the join
SELECT c.name, o.total FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id AND o.total > 1000;
Row multiplication. Joining customers to orders and to addresses at the same time multiplies rows: two orders times three addresses gives six rows per customer, and any SUM is now wrong. Aggregate in a subquery first, then join.
NULL never equals NULL. A join condition on columns that can be NULL silently drops those rows.
Counting with outer joins. COUNT(*) counts Sara's row as 1. Use COUNT(o.id) to count her orders as 0.
In short
- INNER: only matching pairs. LEFT: all left rows,
NULLwhere no match. RIGHT: the mirror. FULL: everything from both sides. CROSS: every combination. - A join returns one row per matching pair, so one-to-many joins repeat the "one" side.
- Put conditions on the optional table in
ON, notWHERE. - Index the join keys and check the plan with
EXPLAIN.
Originally published at abdeldjalilchougui.biz.
Top comments (0)