Sub topic 13
Common join pitfalls
This chapter assumes you can write inner and outer joins in ANSI syntax, you know what the (+) operator does, and you understand how NULL behaves in comparisons. The examples use the standard Oracle HR sample schema. Most join bugs don't raise an error. The query runs and returns the wrong number of rows, or the right number of rows with the wrong totals. Learning to recognize each symptom is faster than reading the query line by line.
Symptoms and likely causes
Start from what you observe in the result, then look for the matching cause.
| Symptom | Likely cause | Where to look |
|---|---|---|
| Far more rows than expected | Missing join condition (Cartesian product) | FROM list, WHERE clause |
| Slightly more rows, inflated sums | One-to-many join fan-out | Join keys, aggregates |
| Fewer rows than expected | NULL join keys, or an outer join turned inner | ON, WHERE, later joins |
| Counts of 1 for empty groups | `COUNT(*)` over NULL-extended rows | Aggregate argument |
| ORA-00918 or ORA-25154 | Ambiguous or wrongly qualified column | SELECT list, USING |
| Natural join returns almost nothing | Unintended shared column names | NATURAL JOIN |
Accidental Cartesian products
A Cartesian product pairs every row of one table with every row of the other. With the comma syntax, you get one by forgetting a join condition. The query below has three tables but only one condition:
SELECT e.last_name, d.department_name, l.city
FROM employees e, departments d, locations l
WHERE e.department_id = d.department_id;employees and departments are joined correctly. Every resulting row is then paired with every row of locations, so the row count is the correct count multiplied by the number of locations. Oracle accepts this without complaint.
ANSI syntax makes this mistake harder. JOIN without ON or USING is a syntax error (typically ORA-00905, missing keyword). When you want a Cartesian product, say so with CROSS JOIN. A reader can then tell the product is deliberate.
SELECT d.department_name, l.city
FROM departments d
CROSS JOIN locations l;A quick check is to count join conditions. A query joining N tables needs at least N-1 of them, one linking each table to the others.
Fan-out: duplicate rows and inflated sums
A join returns one row for each matching pair. If you join a parent row to a child table that has several matching rows, the parent repeats once per child. This is correct, but it surprises people who then aggregate the parent's columns.
In HR, some employees have more than one row in job_history. This query adds up salaries after joining to that table:
SELECT SUM(e.salary) AS total_salary
FROM employees e
JOIN job_history jh ON jh.employee_id = e.employee_id;An employee with two history rows contributes their salary twice. Employees with no history rows contribute nothing, so the total is also missing people. Two errors combine, and the result looks plausible.
The fix is to reduce the child table to one row per join key before joining. An inline view does this:
SELECT e.employee_id, e.last_name, h.job_changes
FROM employees e
JOIN (SELECT employee_id, COUNT(*) AS job_changes
FROM job_history
GROUP BY employee_id) h
ON h.employee_id = e.employee_id;Now h has at most one row per employee, so each employee appears at most once. Use LEFT JOIN instead if employees without history should stay in the result.
Fan-out gets worse when you join two independent child tables to the same parent. If a department has 5 employees and 3 job history entries, joining both gives 15 rows for that department. Aggregate each child separately, then join the aggregates.
NULL join keys
A join condition a.x = b.y is true only when both values are non-NULL and equal. NULL = NULL evaluates to unknown, so rows with a NULL key never match in an inner join. In HR, the employee Kimberely Grant has a NULL department_id. This query leaves her out:
SELECT e.last_name, d.department_name
FROM employees e
JOIN departments d ON e.department_id = d.department_id;In the standard sample data, SELECT COUNT(*) FROM employees returns 107 and this join returns 106. Nothing signals that a row was dropped. To keep her, use an outer join from employees:
SELECT e.last_name, d.department_name
FROM employees e
LEFT OUTER JOIN departments d ON e.department_id = d.department_id;Her department_name shows as NULL. If you need two NULL keys to match each other, which is rare, spell it out:
ON a.x = b.y OR (a.x IS NULL AND b.y IS NULL)This usually prevents Oracle from using an index on the join column, so use it only when you really need that behavior.
Outer joins that quietly become inner joins
You saw the ON versus WHERE difference earlier. Two related cases are worth repeating because they are common in long queries.
A WHERE condition on the outer table rejects the NULL-extended rows. The next query is meant to list all departments with their high earners, but it drops every department without one:
SELECT d.department_name, e.last_name
FROM departments d
LEFT OUTER JOIN employees e ON e.department_id = d.department_id
WHERE e.salary > 10000;The second case is an inner join that follows an outer join. The NULL-extended rows from the first join have a NULL job_id, so the second join discards them:
SELECT d.department_name, e.last_name, j.job_title
FROM departments d
LEFT OUTER JOIN employees e ON e.department_id = d.department_id
JOIN jobs j ON j.job_id = e.job_id;Departments with no employees disappear. Make the later join outer as well (LEFT OUTER JOIN jobs j), or restructure the query so the inner joins come first.
With the (+) syntax the same mistake appears as a forgotten marker. Every condition that references the outer table needs (+), including conditions against constants. Without it, the condition acts as a WHERE filter and removes the NULL-extended rows.
COUNT(*) over outer joins
After a left outer join, a department with no employees still produces one row, with NULLs in the employee columns. COUNT(*) counts rows, so that department reports 1:
SELECT d.department_name, COUNT(*) AS wrong_count
FROM departments d
LEFT OUTER JOIN employees e ON e.department_id = d.department_id
GROUP BY d.department_name;Count a column from the outer table instead. COUNT(column) ignores NULLs, so empty departments report 0:
SELECT d.department_name, COUNT(e.employee_id) AS employee_count
FROM departments d
LEFT OUTER JOIN employees e ON e.department_id = d.department_id
GROUP BY d.department_name;Choose a column that cannot be NULL in a real row, such as the primary key.
Ambiguous column names
When two joined tables both have a column with a given name, you must qualify it. Both employees and departments have department_id, so this fails with ORA-00918 (column ambiguously defined):
SELECT employee_id, department_id
FROM employees e
JOIN departments d ON e.department_id = d.department_id;Qualify the column with a table alias, as in e.department_id. Qualifying every column in a multi-table query is a good habit anyway. It also protects you later: if someone adds a column to one table that shares a name with a column in another, a query that used to work can start failing.
USING reverses the rule. A column named in USING must not carry a qualifier anywhere in the query. Writing e.department_id after JOIN departments d USING (department_id) raises ORA-25154 (column part of USING clause cannot have qualifier). Write the bare name department_id instead. Columns that are not in USING but share a name across the tables still need qualifiers.
NATURAL JOIN and shared column names
NATURAL JOIN joins on every column name the two tables have in common. You don't control which columns that is, and it can change when someone adds a column to either table. In HR, employees and departments share two columns: department_id and manager_id.
SELECT employee_id, last_name, department_name
FROM employees
NATURAL JOIN departments;This joins on both columns. An employee appears only if their department matches and their manager is also the manager of that department. The result is a small fraction of the table, and a reader who expected a plain department join will not see why. Prefer JOIN ... ON or JOIN ... USING (column) so the join columns are written down.
A checklist before you trust a join
- Count the join conditions. N tables need at least N-1.
- Identify the one-to-many relationships. Check whether you aggregate a column from the "one" side after joining the "many" side.
- Ask which join keys can be NULL and whether those rows should survive.
- For every outer join, check each later WHERE condition and each later join for the outer table's columns.
- Make sure
COUNTarguments come from the correct side of an outer join. - Replace
NATURAL JOINwith an explicit condition unless you have verified the shared columns.
Exercise
A query joins departments d to employees e with LEFT OUTER JOIN ... ON e.department_id = d.department_id and groups by d.department_name. It uses COUNT(*), and the department Treasury, which has no employees, shows a count of 1. Why does that happen, and how do you fix it?
Show answer
The outer join keeps Treasury as one row with NULLs in all employee columns, and COUNT(*) counts that row. Change the aggregate to COUNT(e.employee_id). It counts only non-NULL values from the outer table, so Treasury shows 0.
Exercise
This query is meant to list every department and its jobs, but departments with no employees are missing. What is wrong, and what is the fix? SELECT d.departmentname, j.jobtitle FROM departments d LEFT OUTER JOIN employees e ON e.departmentid = d.departmentid JOIN jobs j ON j.jobid = e.jobid;
Show answer
The second join is an inner join. For a department without employees, e.job_id is NULL, so j.job_id = e.job_id is not true and the row is discarded. Change it to LEFT OUTER JOIN jobs j ON j.job_id = e.job_id.
Exercise
You join employees e to job_history jh on employee_id and compute SUM(e.salary). Why is the total wrong, and what is one way to fix it?
Show answer
An employee with several job_history rows is repeated once per row, so their salary is added several times. Employees with no history rows are also excluded. Aggregate job_history to one row per employee in an inline view first, or sum the salaries from employees alone and use EXISTS to test for history.