Before continuing: This entry is part of the JOIN guide. If you are new to the topic, start with JOIN.
Examples
SELECT c.name, p.id AS order_id
FROM customers AS c
INNER JOIN orders AS p
ON p.customer_id = c.id
ORDER BY c.id, p.id;Only customers with at least one order appear. A customer can produce several rows because each order is a separate match.
SELECT c.name, p.id AS order_id
FROM customers AS c
LEFT JOIN orders AS p
ON p.customer_id = c.id
ORDER BY c.id, p.id;Now Peter Hill and Miles Lee appear as well. Because they have no orders, order_id equals NULL.
Differences and trade-offs
The question that decides the JOIN
Before writing the query, phrase a question whose answer you can check:
- “Show me customers who have orders” leads to
INNER JOIN. - “Show me every customer, whether or not they have orders” leads to
LEFT JOIN.
The table to the left of LEFT JOIN is the one kept in full. Changing the order of the tables changes the meaning.
| Aspect | INNER JOIN | LEFT JOIN |
|---|---|---|
| Matching rows | Kept | Kept |
| Unmatched left rows | Dropped | Kept, with right-hand columns set to NULL |
| Typical question | Which items are related? | Which items exist, related or not? |
The filter that can turn a LEFT JOIN into an inner join
A condition on the right table placed in WHERE is evaluated after the joined result is built. If it requires a specific value, rows with no match fail it because they contain NULL.
SELECT c.name, COUNT(p.id) AS shipped
FROM customers AS c
LEFT JOIN orders AS p
ON p.customer_id = c.id
AND p.status = 'shipped'
GROUP BY c.id, c.name
ORDER BY c.id;The status condition is part of the match. Customers with no shipped orders are kept and their count is 0. If you wrote WHERE p.status = 'shipped', they would disappear.
Common mix-ups with INNER JOIN vs LEFT JOIN
Treating NULLs as bad data
In a LEFT JOIN, a NULL from the right table may simply mean there was no match.
Expecting one row per customer without grouping
A customer with three orders produces three matches. To get one row per customer you must aggregate, pick a single match or define another rule.
Filtering the right table in WHERE without checking the goal
That filter can remove exactly the unmatched rows you meant to keep.