Sub topic 17
Common mistakes and how to debug a join
This chapter assumes you can write an INNER JOIN ... ON query, use table aliases, and understand primary and foreign keys. It uses the customers, orders, products and order_items tables from earlier chapters. Most join bugs don't raise an error. The query runs and returns plausible numbers that are wrong, so the skill to build is checking results, not only reading error messages.
A debugging routine
Work from the smallest query outward. Each step answers one question about the row count.
Add one table at a time and count after each step. When the count changes unexpectedly, the join you just added is the cause.
Mistake 1: a missing or wrong join condition
Without a condition that links the tables, the database pairs every row with every row. This is the Cartesian product from earlier in the tutorial. With 3 customers and 4 orders you get 12 rows:
SELECT COUNT(*) AS row_count
FROM customers AS c, orders AS o;The comma form is the easiest place to make this mistake, because forgetting the WHERE raises no error. The explicit JOIN ... ON syntax makes the omission more visible, and standard SQL requires an ON for INNER JOIN. Some databases, MySQL for one, accept INNER JOIN without ON and treat it as a cross join. Don't rely on that.
A subtler version joins on the wrong columns. The query ON o.id = c.id is valid SQL. It matches order 1 to customer 1, which is meaningless. When the key values happen to overlap, this bug returns believable rows. Always check that one side of the condition is a foreign key and the other is the key it references.
A related error is the ambiguous column. If both customers and orders have an id column and you write SELECT id, PostgreSQL reports column reference "id" is ambiguous. Qualify every column with its alias, as in c.id and o.id, even where the database would let you skip it.
Mistake 2: row multiplication that inflates totals
A parent row that matches several child rows appears once per match. This query joins orders to their items and sums the order total:
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders (id),
product_id INTEGER NOT NULL REFERENCES products (id),
quantity INTEGER NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO products (id, name) VALUES (1, 'Pen'), (2, 'Notebook');
INSERT INTO order_items (order_id, product_id, quantity) VALUES
(101, 1, 3),
(101, 2, 1),
(102, 1, 2),
(103, 2, 5);
SELECT SUM(o.total) AS inflated_revenue
FROM orders AS o
INNER JOIN order_items AS i ON i.order_id = o.id;Order 101 has two items, so its total of 50.00 is added twice. The result is 195.00. The orders that have items actually total 145.00 (50 + 75 + 20).
The fix is to make the two sides the same grain before combining them. Either aggregate the many side first, or avoid the join when you only need to test for existence:
SELECT SUM(o.total) AS revenue
FROM orders AS o
WHERE EXISTS (
SELECT 1
FROM order_items AS i
WHERE i.order_id = o.id
);To sum a child column, such as quantity per customer, aggregating after the join is fine, because each child row appears once. The rule is to sum a column only on the side whose rows were not repeated. To spot repetition, compare COUNT(*) with COUNT(DISTINCT o.id) on the joined result. If they differ, parent rows are repeating.
Mistake 3: rows silently disappearing
An inner join drops rows with no match. Two causes are common:
- NULL keys. Order 104 has
customer_id = NULL. The comparisonNULL = 1is unknown, not true, so the row never matches. EvenNULL = NULLis unknown. - Orphans and childless parents. Chloe has no orders, so she never appears.
Reconcile counts to find the lost rows:
SELECT
(SELECT COUNT(*) FROM orders) AS all_orders,
(SELECT COUNT(*)
FROM orders AS o
INNER JOIN customers AS c ON c.id = o.customer_id) AS joined_orders;This returns 4 and 3. To see which rows were lost, use an outer join and keep only the rows without a match:
SELECT o.id AS order_id
FROM orders AS o
LEFT JOIN customers AS c ON c.id = o.customer_id
WHERE c.id IS NULL;
SELECT c.name
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
WHERE o.id IS NULL;The first query returns order 104 and the second returns Chloe. Use IS NULL for these tests, because = NULL never matches.
Mistake 4: filters that change the meaning of the join
With an inner join, a condition in WHERE and the same condition in ON give identical results. With an outer join they don't. A WHERE condition on the optional table removes the NULL-extended rows and quietly turns the outer join back into an inner join. If you debug by switching a join to LEFT JOIN and then add a WHERE o.total > 30, you lose the customers you were trying to see. Put conditions on the optional table in the ON clause when you want to keep unmatched rows.
Mistake 5: keys that look equal but are not
A join compares values exactly. These problems all produce missing matches without an error:
- Different types, such as an integer joined to a text column. Some databases convert implicitly. Others raise an error, and a conversion can also stop an index from being used.
- Trailing spaces or different letter case in text keys, such as
'ab'and'AB '. - Wrapping a join column in a function, such as
ON LOWER(a.code) = b.code. This works but usually prevents an index ona.codefrom being used. Clean the data or store keys in a consistent form instead.
To find mismatches, look at a few unmatched values from each side next to each other and compare them character by character, for example with LENGTH().
Symptom guide
| Symptom | Likely cause | First check |
|---|---|---|
| Far more rows than either table | Missing or wrong `ON` condition | `COUNT(*)` after joining two tables only |
| Slightly more rows than expected | Duplicate keys on the side you assumed was unique | `GROUP BY` the key with `HAVING COUNT(*) > 1` |
| Totals too large | Parent values repeated by a one-to-many join | `COUNT(*)` against `COUNT(DISTINCT parent id)` |
| Fewer rows than expected | NULL keys, orphans, or a `WHERE` filter | Anti-join with `LEFT JOIN ... IS NULL` |
| Query is slow | No index on a join column, or a function on it | `EXPLAIN` the query |
Checking the plan
If the results are correct but the query is slow, ask the database how it will run it. In PostgreSQL and MySQL, prefix the query with EXPLAIN:
EXPLAIN
SELECT c.name, o.id
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id;Look for a full table scan on a large table where you expected an index lookup. Foreign key columns such as orders.customer_id are not always indexed automatically, so add an index on the many side if the plan shows a scan.
Exercise
A query joins orders to order_items and reports SUM(o.total). The result is higher than the sum of total over the orders table filtered to those with items. What is the cause, and how can you confirm it with one query?
Show answer
Orders with several items are repeated once per item, so their totals are counted several times. Confirm it by comparing COUNT(*) with COUNT(DISTINCT o.id) on the joined result. The two numbers differ when parent rows repeat. Fix it by aggregating at the order level or using EXISTS.
Exercise
You run SELECT COUNT(*) FROM orders AS o INNER JOIN customers AS c ON c.id = o.customer_id and get 3, but the orders table has 4 rows. Write a query that returns the missing order and explain why it was dropped.
Show answer
SELECT o.id FROM orders AS o LEFT JOIN customers AS c ON c.id = o.customer_id WHERE c.id IS NULL; returns order 104. Its customer_id is NULL, and a comparison with NULL is never true, so the inner join found no matching customer.