SQL Join Mistakes and How to Spot Them
What you will learn
- Why a total can be counted twice after a join
- What a missing or wrong
ONcondition does - How to read the ambiguous column error
- A checklist to test any join
This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.
1. The dangerous kind of mistake
The worst join mistakes do not give an error. They give a result that looks fine and is wrong. This lesson shows each one, so that you can recognise it, and a way to test for it.
2. A total counted twice
When you join a table to its children, each parent row is repeated once per child. A sum of a parent's column then counts the same value several times:
The money in payments (one payment per paid order) joined to the order lines (several lines per order):
SELECT ROUND(SUM(amount), 2) AS correct_total FROM payments;
correct_total
-------------
233328.89
(1 row)
SELECT ROUND(SUM(p.amount), 2) AS inflated_total
FROM payments AS p
JOIN order_items AS i ON i.order_id = p.order_id;
inflated_total
--------------
678313.8
(1 row)
The balances of accounts joined to their ledger rows (many per account):
SELECT SUM(balance_cents) AS correct_total FROM accounts;
correct_total
-------------
62199130
(1 row)
SELECT SUM(a.balance_cents) AS inflated_total
FROM accounts AS a
JOIN transactions AS t ON t.account_id = a.account_id;
inflated_total
--------------
1164592059
(1 row)
The seats of sections joined to their enrollments (many per section):
SELECT SUM(capacity) AS correct_total FROM sections;
correct_total
-------------
1210
(1 row)
SELECT SUM(sec.capacity) AS inflated_total
FROM sections AS sec
JOIN enrollments AS e ON e.section_id = sec.section_id;
inflated_total
--------------
29275
(1 row)
The second total is far larger: each parent value was added once for every child row. The query ran without a single error.
The cure: sum the parent column before the join, or at the parent's own level (the first query), or aggregate the children in a subquery and join that result (a later chapter). Whenever you join to the "many" side and then add up a column from the "one" side, stop and think.
3. A missing join condition
Forget the ON and you get a cross join (lesson 4.1). The row count is the product of the two tables:
SELECT (SELECT COUNT(*) FROM orders AS c JOIN customers AS p ON p.customer_id = c.customer_id) AS correct_join,
(SELECT COUNT(*) FROM orders AS c CROSS JOIN customers AS p) AS no_condition;
correct_join no_condition
------------ ------------
2600 1092000
(1 row)
SELECT (SELECT COUNT(*) FROM accounts AS c JOIN customers AS p ON p.customer_id = c.customer_id) AS correct_join,
(SELECT COUNT(*) FROM accounts AS c CROSS JOIN customers AS p) AS no_condition;
correct_join no_condition
------------ ------------
450 135000
(1 row)
SELECT (SELECT COUNT(*) FROM sections AS c JOIN courses AS p ON p.course_id = c.course_id) AS correct_join,
(SELECT COUNT(*) FROM sections AS c CROSS JOIN courses AS p) AS no_condition;
correct_join no_condition
------------ ------------
41 779
(1 row)
If a join suddenly returns an enormous number of rows, look for a missing condition first.
4. The wrong columns in ON
A condition that compares the wrong columns gives a valid, meaningless result. Here the child's own id is compared with the parent's key:
SELECT (SELECT COUNT(*) FROM orders AS c JOIN customers AS p ON p.customer_id = c.customer_id) AS right_columns,
(SELECT COUNT(*) FROM orders AS c JOIN customers AS p ON p.customer_id = c.order_id) AS wrong_columns;
right_columns wrong_columns
------------- -------------
2600 420
(1 row)
SELECT (SELECT COUNT(*) FROM accounts AS c JOIN customers AS p ON p.customer_id = c.customer_id) AS right_columns,
(SELECT COUNT(*) FROM accounts AS c JOIN customers AS p ON p.customer_id = c.account_id) AS wrong_columns;
right_columns wrong_columns
------------- -------------
450 300
(1 row)
SELECT (SELECT COUNT(*) FROM sections AS c JOIN courses AS p ON p.course_id = c.course_id) AS right_columns,
(SELECT COUNT(*) FROM sections AS c JOIN courses AS p ON p.course_id = c.section_id) AS wrong_columns;
right_columns wrong_columns
------------- -------------
41 19
(1 row)
The second query returns some rows, because small numbers happen to match. Nothing in the database says that the ids mean the same thing. Always join a foreign key to the primary key it points to (lesson 4.1 showed how to list them).
5. A LEFT JOIN turned into an inner join
A condition on the right table in WHERE removes the unmatched rows (lesson 4.3):
SELECT (SELECT COUNT(*) FROM customers AS p LEFT JOIN orders AS c ON c.customer_id = p.customer_id) AS left_join_rows,
(SELECT COUNT(*) FROM customers AS p LEFT JOIN orders AS c ON c.customer_id = p.customer_id WHERE c.order_id IS NOT NULL) AS after_the_where;
left_join_rows after_the_where
-------------- ---------------
2655 2600
(1 row)
SELECT (SELECT COUNT(*) FROM customers AS p LEFT JOIN accounts AS c ON c.customer_id = p.customer_id) AS left_join_rows,
(SELECT COUNT(*) FROM customers AS p LEFT JOIN accounts AS c ON c.customer_id = p.customer_id WHERE c.account_id IS NOT NULL) AS after_the_where;
left_join_rows after_the_where
-------------- ---------------
514 450
(1 row)
SELECT (SELECT COUNT(*) FROM courses AS p LEFT JOIN sections AS c ON c.course_id = p.course_id) AS left_join_rows,
(SELECT COUNT(*) FROM courses AS p LEFT JOIN sections AS c ON c.course_id = p.course_id WHERE c.section_id IS NOT NULL) AS after_the_where;
left_join_rows after_the_where
-------------- ---------------
42 41
(1 row)
The WHERE c.id IS NOT NULL threw away exactly the parents without children, so the "left join" is now an inner join. Put such conditions in ON, or test with IS NULL only when you want the unmatched rows.
6. The ambiguous column
When both tables have a column with the same name, and you write the name without a table alias, SQL cannot tell which one you mean. This one does give an error, which is good:
SELECT customer_id FROM customers AS p JOIN orders AS c ON c.customer_id = p.customer_id;
OperationalError: ambiguous column name: customer_id
SELECT customer_id FROM customers AS p JOIN accounts AS c ON c.customer_id = p.customer_id;
OperationalError: ambiguous column name: customer_id
SELECT course_id FROM courses AS p JOIN sections AS c ON c.course_id = p.course_id;
OperationalError: ambiguous column name: course_id
ambiguous column name means the name exists in both tables. Fix it with the alias in front of the column, for example p.customer_id or c.customer_id. A good habit: write every column with its alias in a join, even when it is not ambiguous.
7. A checklist for every join
- Which row does the result have one of? (an order, a line, a customer)
- Does each
ONcompare a foreign key with the primary key it points to? - Is the row count what I expect? Compare with the table I start from.
- Do any joins go from a parent to its children? Then rows multiply: do not add up parent columns.
- Is a
LEFT JOINreally a left join? No right-table condition inWHERE. - Do the totals agree with a simple query on one table?
Worked example: the total that was too high
A report says orders are worth 3.2 million, but finance says 1.1 million.
| Step | Finding |
|---|---|
| 1 | the query joins orders to order_items and sums orders.total |
| 2 | each order has about 2 to 3 lines, so each total was added 2 to 3 times |
| 3 | fix: sum quantity * unit_price of the lines, or sum orders.total without the join |
| 4 | check: the new figure agrees with finance |
The cause was a sum of a parent column after a join to the child. The numbers are made up.
Common mistakes
- Summing a parent column after joining to its children.
- Forgetting the
ONcondition. - Joining on columns that are not a foreign key and its key.
- A right-table condition in
WHEREafter aLEFT JOIN. - Leaving a column unqualified when both tables have it.
- Trusting a result without checking the row count.
Key takeaways
- The worst mistakes give wrong numbers, not errors; test the row count and a total.
- Joining to the "many" side repeats the "one" side's values: do not sum them afterwards.
- A missing
ONis a cross join; a wrongONis silently meaningless. WHEREon the right table cancels aLEFT JOIN.- An
ambiguous column nameerror is fixed with a table alias.
Practice
1. Why does SUM(a.balance_cents) become too large after joining accounts to transactions?
Show answer
Each account row is repeated once for every transaction, so its balance is added many times.
2. What does a join with no ON condition return?
Show answer
Every row of one table paired with every row of the other (a cross join).
3. What does ambiguous column name: customer_id mean?
Show answer
Both tables have a column called customer_id and the query did not say which; use an alias (c.customer_id).
4. How do you check a join quickly?
Show answer
Compare its row count with the table you start from, and compare a total with a simple one-table query.
5. What do you do if a WHERE on the right table makes a LEFT JOIN lose rows?
Show answer
Move the condition into the ON clause.
6. Which columns should an ON compare?
Show answer
A foreign key with the primary key it points to.