A friendly introduction to SQL joins
Inner, left and full joins explained with one small example you can run in five minutes
2 min read ·
Joins are where most people's SQL confidence goes to die. They do not need to. A join does one thing: it puts rows from two tables side by side when they share a value. Everything else is a question of what to do with the rows that do not match.
The example
Two tiny tables: customers, and the orders they placed.
| customers.id | name |
|---|---|
| 1 | Asha |
| 2 | Ben |
| 3 | Chen |
| orders.id | customer_id | total |
|---|---|---|
| 10 | 1 | 40 |
| 11 | 1 | 15 |
| 12 | 2 | 60 |
| 13 | 9 | 25 |
Notice two awkward rows: Chen has no orders, and order 13 belongs to customer 9, who does not exist.
Inner join: only the matches
SELECT c.name, o.id AS order_id, o.total
FROM customers c
JOIN orders o ON o.customer_id = c.id;
You get Asha twice and Ben once. Chen disappears (no orders) and order 13 disappears (no customer). An inner join keeps only rows that match on both sides.
Left join: keep everything on 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;
Now Chen comes back, with empty (NULL) order columns. Use a left join when the question is about the left table: “every customer and their orders, if any”.
A handy trick:
LEFT JOIN ... WHERE o.id IS NULLfinds customers who never ordered.
Full join: keep everything
SELECT c.name, o.id AS order_id, o.total
FROM customers c
FULL JOIN orders o ON o.customer_id = c.id;
Chen and order 13 both appear, each with empty columns on the side that is missing. Full joins are mostly for checking data: they show you what does not line up.
Picking the right one
| Question | Join |
|---|---|
| Orders with their customer's name | Inner |
| Every customer, even without orders | Left |
| What does not match between two tables? | Full |
Three mistakes to avoid
- Joining on the wrong column.
o.id = c.idruns without error and returns nonsense. - Forgetting duplicates. One customer with three orders becomes three rows. Sums of customer fields will triple.
- Filtering a left join in WHERE.
WHERE o.total > 20quietly turns a left join back into an inner one. Put the condition in theONclause instead.
Run the three queries above on the tiny tables, look at the rows, and joins stop being magic.
Responses