Sub topic 10
USING and NATURAL JOIN
Oracle offers two shorthand forms of the ANSI join. USING names the columns to join on. NATURAL JOIN finds the columns by itself. Both save typing. Both also change how you can refer to the join columns, and NATURAL JOIN can quietly change what a query means. This chapter covers how each works, the errors you will see, and when to avoid them.
Prerequisites
This chapter assumes you can:
- Write an
INNER JOIN ... ONand aLEFT OUTER JOIN ... ON. - Use table aliases.
- Explain what
NULLdoes to a comparison.
The examples use the Oracle HR sample schema. The tables are employees, departments, locations and job_history.
USING: naming the shared column
USING replaces the ON condition when the join columns have the same name in both tables. It joins on equality of the listed columns.
SELECT department_id, d.department_name, e.last_name
FROM employees e
JOIN departments d USING (department_id);This is the same join as ON e.department_id = d.department_id. There are three differences.
- The column list in
USINGis in parentheses, even for a single column. - The join column appears once in the result. With
SELECT *, theUSINGcolumns come first, followed by the remaining columns of the left table and then of the right table. - The join column must not have a qualifier anywhere in the query.
The no-qualifier rule
Oracle rejects any table alias on a USING column, in the select list and also in WHERE, GROUP BY and ORDER BY.
-- Fails with ORA-25154: column part of USING clause cannot have qualifier
SELECT e.department_id, d.department_name
FROM employees e
JOIN departments d USING (department_id);Remove the alias and the query works:
SELECT department_id, d.department_name
FROM employees e
JOIN departments d USING (department_id)
WHERE department_id > 50
ORDER BY department_id;Columns that are not in the USING list keep their normal rules. If both tables have a column with the same name that is not in USING, you must qualify it, or Oracle raises ORA-00918: column ambiguously defined. In the HR schema, manager_id is such a column, because it exists in both employees and departments.
Joining on several columns
List more than one column, separated by commas. All of them must match.
SELECT employee_id, job_id, e.department_id AS current_dept,
j.department_id AS past_dept
FROM employees e
JOIN job_history j USING (employee_id, job_id);This returns employees whose current job is one they held before. Because department_id is not in the USING list, it exists in both tables, so you qualify each copy and give it an alias.
USING with outer joins
USING works with LEFT, RIGHT and FULL OUTER JOIN. For a FULL OUTER JOIN, the unqualified USING column returns the non-null value from whichever side has a row.
SELECT department_id, e.last_name, d.department_name
FROM employees e
FULL OUTER JOIN departments d USING (department_id);An employee with no department shows NULL in department_id, because neither side has a value. A department with no employees shows its own department_id and NULL for last_name. With ON, you would have to write COALESCE(e.department_id, d.department_id) yourself to get the same effect.
NATURAL JOIN: letting Oracle choose the columns
NATURAL JOIN joins on every column name that appears in both tables. You write no column list and no condition.
SELECT department_name, city
FROM departments
NATURAL JOIN locations;departments and locations share only location_id, so this is equivalent to JOIN locations USING (location_id).
The rules mirror USING:
- Oracle compares the columns for equality.
- The common columns appear once in the result.
- You cannot qualify them. Oracle raises
ORA-25155: column used in NATURAL join cannot have qualifier. - You can combine it with outer joins, as in
NATURAL LEFT OUTER JOIN.
The shared-column trap
NATURAL JOIN matches by name only. It does not know about foreign keys. If two tables share a column name that is not meant for joining, it becomes part of the join condition.
SELECT employee_id, last_name, department_name
FROM employees
NATURAL JOIN departments;In HR, both tables have department_id and manager_id. The query above is really:
SELECT e.employee_id, e.last_name, d.department_name
FROM employees e
JOIN departments d
ON e.department_id = d.department_id
AND e.manager_id = d.manager_id;The query returns only employees whose own manager is also the manager of their department. It does not raise an error. Most employees silently disappear from the result.
Silent changes over time
A NATURAL JOIN that works today can change meaning later.
- If someone adds a column such as
created_dateto both tables, it joins on that column too, and rows drop out. - If someone renames a join column in one table, the join may become a Cartesian product. A natural join between tables with no common column names returns every combination of rows, like a
CROSS JOIN.
A query that names its join columns, with ON or USING, fails loudly in these cases or keeps working. A natural join does neither.
Comparing the three forms
| Feature | `ON` | `USING` | `NATURAL JOIN` |
|---|---|---|---|
| Join columns | You write each condition | You list column names | Every same-named column |
| Column names must match | No | Yes | Yes |
| Non-equality conditions | Yes | No | No |
| Extra filters in the join clause | Yes | No | No |
| Join column qualified with alias | Yes | No (ORA-25154) | No (ORA-25155) |
| Join column in `SELECT *` | Appears from each table | Appears once, first | Appears once, first |
| Affected by new columns | No | No | Yes |
The diagram shows a way to choose between them.
Limits of USING with outer joins
You cannot mix USING and ON in the same join. You also cannot add AND e.salary > 10000 inside a USING join. This matters for outer joins. The earlier chapters showed that a filter on the outer table in WHERE removes the NULL-extended rows, and that the filter must be in ON to keep them.
With USING, filter the outer table before the join, in an inline view:
SELECT department_id, d.department_name, e.last_name
FROM departments d
LEFT OUTER JOIN (SELECT employee_id, last_name, department_id
FROM employees
WHERE salary > 10000) e
USING (department_id);This keeps every department. Departments with no high earner show NULL for last_name. If you find yourself wrapping tables in inline views only to keep USING, switch to ON. It is usually clearer.
Joining three or more tables
You can chain USING joins, but be careful. Each USING column is matched against the result of the joins to its left. If the column name appears in more than one of the earlier tables, the reference can become ambiguous. This is common with ID columns that every table carries.
SELECT department_id, location_id, e.last_name, l.city
FROM employees e
JOIN departments d USING (department_id)
JOIN locations l USING (location_id);This works because location_id exists only in departments and locations. If employees also had a location_id, the second join would be ambiguous. For chains of joins, ON is easier to read and survives schema changes better.
Mixing in the older syntax
Neither USING nor NATURAL JOIN has an equivalent in the comma syntax, and (+) cannot be combined with them. When you convert an old (+) query, write the join condition with ON. Use USING only if the column names match and you are happy to give up the alias on that column.
Practical guidance
- Prefer
ONfor production code. It states the condition explicitly and allows aliases, filters and non-equality tests. - Use
USINGfor simple equi-joins on a same-named key, especially when you want one copy of the key inSELECT *. - Avoid
NATURAL JOINin code that other people maintain or that must survive schema changes. Its behavior depends on column names you cannot see in the query. - When a
USINGquery raisesORA-25154, remove the alias from that column and nowhere else.
Exercise
The query SELECT e.department_id, d.department_name FROM employees e JOIN departments d USING (department_id); fails with ORA-25154. Rewrite it so that it works, and then write an equivalent query that uses ON instead of USING and keeps the e.department_id reference.
Show answer
Remove the alias from the USING column: SELECT departmentid, d.departmentname FROM employees e JOIN departments d USING (departmentid); The ON version can keep the alias: SELECT e.departmentid, d.departmentname FROM employees e JOIN departments d ON e.departmentid = d.department_id; Oracle forbids a qualifier on any column named in USING, but an ON join has no such restriction.
Exercise
A report uses SELECT last_name, department_name FROM employees NATURAL JOIN departments; and returns about a quarter of the employees you expect. Explain why, and give a corrected query.
Show answer
employees and departments share two column names in the HR schema, departmentid and managerid. NATURAL JOIN uses both, so only employees whose managerid equals their department's managerid are returned. The fix is to name the intended join column: SELECT lastname, departmentname FROM employees JOIN departments USING (departmentid); Using ON e.departmentid = d.department_id works equally well.
Exercise
You want every department listed, with only employees earning more than 10000 shown. Can you write this as a LEFT OUTER JOIN with USING (department_id) and the salary test in the join clause? If not, what do you do?
Show answer
No. USING cannot be combined with extra conditions, and putting the salary test in WHERE would remove departments that have no high earner. Either use ON with AND e.salary > 10000 in the join condition, or join to an inline view that already filters employees: LEFT OUTER JOIN (SELECT employeeid, lastname, departmentid FROM employees WHERE salary > 10000) e USING (departmentid).