Sub topic 3
Joining Tables in Oracle: FULL OUTER JOIN and Related Joins
This chapter assumes you know basic SELECT, WHERE and ORDER BY, primary and foreign keys, table aliases, and how NULL behaves. The examples use the HR sample schema, where employees has 107 rows and departments has 27.
FULL OUTER JOIN
A FULL OUTER JOIN keeps unmatched rows from both tables. Matched rows appear once. Unmatched rows from either side appear with NULL in the other table's columns.
SELECT e.last_name, d.department_name
FROM employees e
FULL OUTER JOIN departments d
ON e.department_id = d.department_id;What (+) cannot do
The (+) operator marks one side as optional, so it cannot express a FULL OUTER JOIN. Use ANSI syntax when you need unmatched rows from both tables. The (+) operator also cannot be used in a condition that contains OR.
USING and NATURAL JOIN
USING names the shared column. The column appears once in the result and must not carry a table alias.
SELECT department_id, d.department_name, e.last_name
FROM employees e
JOIN departments d USING (department_id);NATURAL JOIN matches every column that has the same name in both tables. In HR, employees and departments both have manager_id, so this query joins on two columns at once:
SELECT last_name, department_name
FROM employees
NATURAL JOIN departments;Self joins and non-equi joins
A self join joins a table to itself using two aliases. This query lists each employee with the manager's last name:
SELECT e.last_name AS employee, m.last_name AS manager
FROM employees e
JOIN employees m ON e.manager_id = m.employee_id;A non-equi join uses an operator other than =. This query pairs each employee with colleagues who earn more:
SELECT e.last_name, m.last_name AS higher_paid
FROM employees e
JOIN employees m ON m.salary > e.salary;Cross joins and Cartesian products
A CROSS JOIN pairs every row with every row. With the HR tables it returns 107 × 27 = 2,889 rows.
SELECT e.last_name, d.department_name
FROM employees e
CROSS JOIN departments d;A comma join with no join condition does the same thing. It is the most common cause of an accidental Cartesian product.
Common join pitfalls
- Duplicate rows: if the join column is not unique on one side, each match repeats.
- Missing rows: NULL never equals NULL, so employees with a NULL department_id drop out of an inner join. A FULL OUTER JOIN keeps them.
Exercise
You need one result that includes employees with no department and departments with no employees. Which join do you use, and why not the (+) operator?
Show answer
Use FULL OUTER JOIN. The (+) operator marks only one side as optional, so it cannot keep unmatched rows from both tables.