Sub topic 7
Joining Three or More Tables
This chapter assumes you can write a two-table inner join and a LEFT OUTER JOIN, and that you know primary keys, foreign keys, table aliases and NULL. Examples use the Oracle HR sample schema: employees, departments, locations, countries and job_history.
How a multi-table join is evaluated
Oracle joins two row sources at a time. The result of the first join becomes the left input of the next one, so a three-table query is one join feeding another. The optimizer is free to reorder inner joins for speed. Logically, though, you should read the FROM clause from top to bottom.
Three consequences follow from this model:
- Each new table needs its own join condition. N tables need at least N-1 conditions.
- An
ONclause can refer to the table being joined and to tables that appear earlier in theFROMclause. - With outer joins, the order of the joins can change the result.
ANSI syntax: one JOIN ... ON per table
Add one JOIN ... ON clause for each additional table:
SELECT e.last_name, d.department_name, l.city
FROM employees e
JOIN departments d ON e.department_id = d.department_id
JOIN locations l ON d.location_id = l.location_id;JOIN on its own means INNER JOIN. Each ON clause links the new table to a table already in the chain. Here locations joins to departments, not to employees, because location_id lives in departments.
A fourth table follows the same pattern:
SELECT e.last_name, d.department_name, l.city, c.country_name
FROM employees e
JOIN departments d ON e.department_id = d.department_id
JOIN locations l ON d.location_id = l.location_id
JOIN countries c ON l.country_id = c.country_id;The chain follows the foreign keys: employee to department, department to location, location to country.
The comma syntax: conditions go in WHERE
The older syntax lists all tables after FROM and puts every join condition in WHERE, combined with AND:
SELECT e.last_name, d.department_name, l.city
FROM employees e, departments d, locations l
WHERE e.department_id = d.department_id
AND d.location_id = l.location_id;This returns the same rows as the ANSI version. The risk is that join conditions and ordinary filters share one WHERE clause, which makes a missing join condition harder to spot. If you leave out d.location_id = l.location_id, Oracle pairs every employee-department row with every location. That is a Cartesian product.
Mixing inner and outer joins: order matters
When every join is an inner join, the order does not change the result. Once an outer join is in the chain, a later inner join can quietly undo it.
Start with a chain of outer joins. In the HR data, one employee (Grant) has no department. This query keeps her:
SELECT e.last_name, d.department_name, l.city
FROM employees e
LEFT OUTER JOIN departments d ON e.department_id = d.department_id
LEFT OUTER JOIN locations l ON d.location_id = l.location_id;For employees without a department, d.department_name and l.city are NULL. The second LEFT OUTER JOIN is needed. Without it, the next version would remove her.
Now change the second join to an inner join:
SELECT e.last_name, d.department_name, l.city
FROM employees e
LEFT OUTER JOIN departments d ON e.department_id = d.department_id
JOIN locations l ON d.location_id = l.location_id;For an employee with no department, the intermediate row has d.location_id set to NULL. The condition NULL = l.location_id is never true, so the inner join discards the row. The query now returns only employees who have a department with a location, even though it begins with a LEFT OUTER JOIN.
Use this rule for chains: after an outer join, every table that hangs off the optional table must also be outer joined if you want to keep the unmatched rows.
Sometimes you want a different result. For example, you may want to include a department only when it has a location, while still keeping all employees. Combine the two inner tables in an inline view, then outer join to the view:
SELECT e.last_name, dl.department_name, dl.city
FROM employees e
LEFT OUTER JOIN (
SELECT d.department_id, d.department_name, l.city
FROM departments d
JOIN locations l ON d.location_id = l.location_id
) dl ON e.department_id = dl.department_id;The inner join happens inside the view, so the outer join still keeps every employee.
The (+) operator across several tables
With the comma syntax, you mark each join condition that should keep unmatched rows. The (+) goes on the column of the table that may lack matches. This is the (+) version of the chain of outer joins above:
SELECT e.last_name, d.department_name, l.city
FROM employees e, departments d, locations l
WHERE e.department_id = d.department_id(+)
AND d.location_id = l.location_id(+);Both conditions carry a (+). If you leave it off the second condition, d.location_id = l.location_id becomes a plain filter. Employees with no department are then removed, which is the same effect as the inner join in the previous section.
The comma syntax is also limited when you join many tables. For example, a table can be the outer-joined side of a (+) against only one other table in a query, and Oracle raises ORA-01417 if you break that rule. A later chapter covers these limits. ANSI joins do not have them.
Watch for row multiplication
A join returns one row for every matching combination. If you join through a table that has several rows per parent, the parent rows repeat. The job_history table stores one row per previous job, so an employee with two earlier jobs appears twice:
SELECT e.last_name, d.department_name, jh.job_id AS previous_job
FROM employees e
JOIN departments d ON e.department_id = d.department_id
LEFT OUTER JOIN job_history jh ON jh.employee_id = e.employee_id
ORDER BY e.last_name;This is correct output, but it breaks any aggregate you compute on columns from the parent table. SUM(e.salary) over this result counts a salary once per history row. There are two usual remedies:
- Aggregate the many-side table in an inline view first (
GROUP BY employee_id), then join the one-row-per-employee result. - Count with
COUNT(DISTINCT e.employee_id)when you only need counts. This does not fixSUM.
Ambiguous columns and USING
When several tables share a column name, you must qualify it with a table alias. department_id exists in both employees and departments, so writing it without a prefix in a SELECT or WHERE raises ORA-00918: column ambiguously defined.
USING removes the ambiguity for the join column, but it comes with a rule: you must not qualify that column anywhere in the query.
SELECT department_id, d.department_name, e.last_name
FROM employees e
JOIN departments d USING (department_id);Writing e.department_id or d.department_id here raises ORA-25154: column part of USING clause cannot have qualifier. In a longer chain, USING only works when the named column has the same name in both of the tables being joined. Where the names differ, as with departments.location_id and locations.location_id, use ON.
Choosing a style for larger queries
| Concern | ANSI `JOIN ... ON` | Comma with `(+)` |
|---|---|---|
| Where join logic lives | `ON` clauses, next to each table | Mixed with filters in `WHERE` |
| Missing join condition | Syntax error | Silent Cartesian product |
| Chains of outer joins | Each join is explicit | Every condition needs its own `(+)` |
| Full outer join | Supported | Not supported in one join |
| Reading order | Top to bottom | Must match conditions to tables by hand |
For queries with three or more tables, prefer ANSI syntax. You will still meet (+) in older code, and the rewrite rules are covered in the chapter on converting (+) queries.
Practice
Exercise
A query starts with FROM employees e LEFT OUTER JOIN departments d ON e.department_id = d.department_id and then adds JOIN locations l ON d.location_id = l.location_id. Employees with no department disappear from the result. Why, and what is the smallest change that keeps them?
Show answer
For an employee with no department, d.locationid is NULL in the intermediate row. The condition d.locationid = l.locationid evaluates to unknown, so the inner join removes the row. Change the second join to LEFT OUTER JOIN locations l ON d.locationid = l.location_id so unmatched rows pass through.
Exercise
Rewrite this query with ANSI syntax and say how many join conditions it needs. SELECT e.lastname, d.departmentname, l.city FROM employees e, departments d, locations l WHERE e.departmentid = d.departmentid(+) AND d.locationid = l.locationid(+);
Show answer
SELECT e.lastname, d.departmentname, l.city FROM employees e LEFT OUTER JOIN departments d ON e.departmentid = d.departmentid LEFT OUTER JOIN locations l ON d.locationid = l.locationid; It needs two join conditions, one fewer than the three tables.
Exercise
You join employees to job_history with a LEFT OUTER JOIN and compute SUM(e.salary) per department. The totals are too high. What causes this and how do you fix it?
Show answer
Employees with several jobhistory rows appear once per history row, so their salary is added several times. Aggregate jobhistory in an inline view (one row per employee) before joining, or compute the salary sum in a query that does not join job_history.