Joins are not just syntax: they define which facts are combined and how many output rows represent the business question. Before writing SQL, identify the grain, keys, relationship cardinality, duplicate behaviour and treatment of unmatched rows.
Example schema
Assume customers(customer_id, name), orders(order_id, customer_id, order_date, amount), and order_items(order_id, product_id, quantity). One customer can have many orders and one order can have many items.
INNER and LEFT JOIN
SELECT c.customer_id, c.name, o.order_id, o.amount
FROM customers AS c
JOIN orders AS o
ON o.customer_id = c.customer_id;
An inner join returns only customers with a matching order. To preserve customers with no orders:
SELECT c.customer_id, c.name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id;
Unmatched order columns are NULL. Find customers without orders by checking a non-nullable right-side key in a WHERE clause.
Many-to-many and inflated totals
Joining orders to order_items changes the grain to one row per item. If an order-level amount is repeated across three items, summing it after the join counts it three times. Aggregate at the intended grain first, or sum item quantity multiplied by item price.
SELECT o.order_id,
SUM(oi.quantity * oi.unit_price) AS item_revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
GROUP BY o.order_id;
Join conditions and NULLs
For inner joins, a filter in ON or WHERE often has the same result. For a left join, putting a right-table filter in WHERE removes unmatched rows and changes the meaning to an inner join. Use COUNT(o.order_id) rather than COUNT(*) when counting matched orders per customer.
Practical debugging sequence
- Write the expected one-row grain.
- Check key uniqueness on both sides.
- Count rows before and after each join.
- Inspect a duplicated key with a small query.
- Reconcile a total to a trusted source.
Common mistakes and FAQs
Common errors include joining on a name instead of a key, forgetting date boundaries, using DISTINCT to hide multiplication, and treating NULL as zero. A FULL OUTER JOIN is not available in every engine; verify dialect support and use a careful UNION alternative when needed.
Next practise the SQL Interview Guide and compare joins with window functions. Further reading: MySQL join documentation.