Sub topic 3
Keeping Unmatched Rows with LEFT and RIGHT OUTER JOIN
This chapter assumes you can write a basic SELECT with WHERE and ORDER BY, and that you know primary keys, foreign keys, table aliases and how NULL behaves in comparisons. It also assumes you have read the chapter on inner joins. The examples use the Oracle HR sample schema (employees, departments, locations).
Why inner joins lose rows
An inner join returns a row only when the join condition finds a match on both sides. A department with no employees has nothing to match, so it disappears from the result. An employee whose department_id is NULL also disappears, because NULL = anything is never true.
Often that is what you want. Sometimes the unmatched rows are the point of the report: "list every department, even empty ones", or "show every customer, including those with no orders". An outer join keeps those rows.
LEFT OUTER JOIN
A LEFT OUTER JOIN returns every row from the table written before the JOIN keyword (the left table). If a left row has no match on the right, Oracle still returns it. It fills every column that comes from the right table with NULL.
SELECT d.department_name, e.last_name
FROM departments d
LEFT OUTER JOIN employees e
ON e.department_id = d.department_id
ORDER BY d.department_name, e.last_name;Two things happen in this query:
- A department with three employees produces three rows, one per match.
- A department with no employees produces one row, with
NULLinlast_name.
The left table is called the preserved table, because none of its rows can be dropped by the join condition. The right table is the null-supplying table, because it supplies NULLs when no match exists.
The word OUTER is optional. LEFT JOIN and LEFT OUTER JOIN are the same thing. This tutorial writes OUTER because it makes the intent obvious to readers.
RIGHT OUTER JOIN
A RIGHT OUTER JOIN is the mirror image. It preserves every row of the table written after the JOIN keyword.
SELECT d.department_name, e.last_name
FROM employees e
RIGHT OUTER JOIN departments d
ON e.department_id = d.department_id;This returns the same rows as the LEFT OUTER JOIN in the previous section. Only the order of the tables in the FROM clause changed, and the keyword changed with it. Any right join can be rewritten as a left join by swapping the two tables.
Most teams standardize on LEFT OUTER JOIN. If the preserved table is always the first one you read, queries are easier to scan, and long chains of joins stay consistent. Use RIGHT OUTER JOIN only when it avoids reordering a long FROM clause that you are editing.
| Join type | Preserved table | Table that gets `NULL`s |
|---|---|---|
| `INNER JOIN` | None | None |
| `LEFT OUTER JOIN` | Left (before `JOIN`) | Right |
| `RIGHT OUTER JOIN` | Right (after `JOIN`) | Left |
| `FULL OUTER JOIN` | Both | Both (covered in its own chapter) |
Finding rows that have no match
A common use of an outer join is to find the unmatched rows themselves. The pattern is to outer join, then keep only the rows where the null-supplying side is NULL.
SELECT d.department_id, d.department_name
FROM departments d
LEFT OUTER JOIN employees e
ON e.department_id = d.department_id
WHERE e.employee_id IS NULL;This returns departments that have no employees. The test must be on a column that can never be NULL in a real match. The primary key e.employee_id is the right choice. If you tested a nullable column such as e.commission_pct, you would also return departments whose employees simply have no commission, which is a different and wrong answer.
The mirror question is "which employees have no department?" Here the employees table is preserved:
SELECT e.employee_id, e.last_name
FROM employees e
LEFT OUTER JOIN departments d
ON e.department_id = d.department_id
WHERE d.department_id IS NULL;The WHERE filter here is applied after the join, which is why it can test for the NULLs the join produced. The next chapter looks closely at how that differs from putting a condition in ON.
Counting with outer joins
Aggregates are where outer joins most often go wrong. Compare these two queries:
SELECT d.department_name,
COUNT(*) AS wrong_count,
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
ORDER BY d.department_name;For a department with no employees, the join still outputs one row, filled with NULLs on the employee side.
COUNT(*)counts rows, so it reports 1 for that department. This is wrong.COUNT(e.employee_id)counts only non-NULLvalues, so it reports 0. This is correct.
Whenever you count across an outer join, count a non-nullable column from the null-supplying table, not *.
Chaining outer joins
Joins are evaluated left to right, and each join sees the result of the previous one. This creates a trap when you mix outer and inner joins.
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;Take an employee with no department. The first join keeps that employee and sets d.location_id to NULL. The second join compares NULL = l.location_id, which is never true. Because that join is also a LEFT OUTER JOIN, the employee row survives, with NULL for city.
Now change the second join to a plain 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;The inner join requires a match in locations. The employee without a department has none, so that employee vanishes, and the first outer join has no visible effect. The query silently behaves like an inner join across both tables.
Edge cases to keep in mind
NULLkeys never match. A left row whose join column isNULLis preserved, but it never pairs with any right row, even a right row whose join column is alsoNULL.- Matches multiply rows. The preserved row appears once for each match. Joining departments to employees returns many rows per department. If you then join a second one-to-many table, such as job history, the counts multiply. Aggregate each side in a subquery before joining if you need totals.
- Ambiguous column names. If both tables have a column with the same name, such as
department_id, you must qualify it with the alias. In an outer join it also matters which alias you pick:d.department_idis neverNULLin the preserved departments table, whilee.department_idisNULLfor unmatched departments. - Unmatched rows appear once. A preserved row with no match yields exactly one output row, not zero and not several.
Summary of the working model
- The
FROMclause and itsJOINs produce a set of rows, from left to right. - For each preserved row, Oracle looks for right rows that satisfy the
ONcondition. - Matches produce one output row each. If there are none, one row with
NULLs on the null-supplying side is produced. WHERE,GROUP BYand the select list then work on that combined result.
Step 4 is why a WHERE condition on the null-supplying table can undo the outer join. That is the topic of the next chapter.
Exercise
Write a query that lists every department with the number of employees in it, including departments with no employees (which must show 0). Which column do you pass to COUNT, and why?
Show answer
SELECT d.departmentname, COUNT(e.employeeid) AS employeecount FROM departments d LEFT OUTER JOIN employees e ON e.departmentid = d.departmentid GROUP BY d.departmentname; Pass e.employee_id, a primary key from the null-supplying table. It is NULL only on the NULL-extended row, so empty departments count 0. COUNT(*) would count that extra row and return 1.
Exercise
Rewrite this RIGHT OUTER JOIN as a LEFT OUTER JOIN that returns the same rows: SELECT d.departmentname, e.lastname FROM employees e RIGHT OUTER JOIN departments d ON e.departmentid = d.departmentid;
Show answer
SELECT d.departmentname, e.lastname FROM departments d LEFT OUTER JOIN employees e ON e.departmentid = d.departmentid; Swap the two tables in the FROM clause and change RIGHT to LEFT. The preserved table, departments, stays the same.
Exercise
A query starts with employees e LEFT OUTER JOIN departments d ON e.departmentid = d.departmentid and then adds JOIN locations l ON d.locationid = l.locationid. An employee with no department is missing from the result. Why, and what is the fix?
Show answer
The employee's d.location_id is NULL, so the inner join to locations finds no match and removes the row. Change the second join to LEFT OUTER JOIN so the employee is kept with NULL for the city.