Sub topic 13
USING and NATURAL JOIN shorthand
This chapter assumes you can write an INNER JOIN ... ON query, use table aliases, and recognize primary keys and foreign keys. Here you will learn two shorthand forms of the join condition, USING and NATURAL JOIN. You will also learn when each is safe to use and why many teams avoid the second one.
Why the shorthands exist
Many schemas name a foreign key column the same as the primary key it points to. A department_id column in staff references department_id in departments. Writing ON s.department_id = d.department_id then repeats the same name on both sides. SQL offers two shortcuts for this case:
USING (column_list)names the shared columns explicitly.NATURAL JOINfinds the shared columns on its own.
Both only produce equality conditions, and both require the columns to have identical names in the two tables.
A schema with matching column names
The sample tables from earlier chapters name their keys id and customer_id, so USING cannot join them. This chapter uses a second pair of tables whose key columns share a name.
CREATE TABLE departments (
department_id INTEGER PRIMARY KEY,
department_name VARCHAR(100) NOT NULL
);
CREATE TABLE staff (
staff_id INTEGER PRIMARY KEY,
staff_name VARCHAR(100) NOT NULL,
department_id INTEGER REFERENCES departments (department_id)
);
INSERT INTO departments (department_id, department_name) VALUES
(1, 'Sales'), (2, 'Support'), (3, 'Legal');
INSERT INTO staff (staff_id, staff_name, department_id) VALUES
(10, 'Ada', 1),
(11, 'Ben', 1),
(12, 'Chloe', 2),
(13, 'Dev', NULL);Legal has no staff, and Dev has no department. An inner join therefore returns three rows: Ada and Ben in Sales, and Chloe in Support.
The USING clause
Here is the familiar form, followed by the USING form.
-- With ON
SELECT s.staff_name, d.department_name
FROM staff AS s
INNER JOIN departments AS d
ON d.department_id = s.department_id;
-- With USING
SELECT staff_name, department_name
FROM staff
INNER JOIN departments USING (department_id);Both queries return the same three rows. USING (department_id) means "pair rows where department_id is equal in both tables." It is an ordinary inner join, so rows with a NULL key still disappear, because NULL = NULL is not true.
One merged column in the output
USING also changes the result's columns. The joined column is merged into a single column, and it can be referenced without a table qualifier.
SELECT *
FROM staff
INNER JOIN departments USING (department_id);In PostgreSQL and MySQL, the output columns are department_id, staff_id, staff_name, department_name. The merged column comes first and appears once. With ON, SELECT * would return department_id twice, which causes trouble when you load the result into a client that keys values by column name.
Joining on several columns
List more than one column, separated by commas. Every listed column must exist in both tables, and all must be equal.
CREATE TABLE department_targets (
department_id INTEGER NOT NULL,
target_year INTEGER NOT NULL,
target DECIMAL(10, 2) NOT NULL,
PRIMARY KEY (department_id, target_year)
);
CREATE TABLE department_results (
department_id INTEGER NOT NULL,
target_year INTEGER NOT NULL,
result DECIMAL(10, 2) NOT NULL,
PRIMARY KEY (department_id, target_year)
);
SELECT department_id, target_year, target, result
FROM department_targets
INNER JOIN department_results USING (department_id, target_year);This is equivalent to ON t.department_id = r.department_id AND t.target_year = r.target_year, with both columns merged in the output.
Limits of USING
- Names must match.
orders.customer_idandcustomers.idcannot be joined withUSING. UseON. - Equality only. Range conditions such as
o.total >= t.min_totalneedON. - No extra conditions. Unlike
ON, theUSINGlist cannot carry additional predicates. Put them inWHERE. - Qualified references differ by database. PostgreSQL and MySQL accept
staff.department_idafter aUSINGjoin. Oracle rejects a qualified reference to aUSINGcolumn with an error. If portability matters, leave the column unqualified. - Not available everywhere. SQL Server supports neither
USINGnorNATURAL JOIN.
Chaining USING across several tables
USING works in a multi-table join, but each USING column must exist in the left-hand side built so far and in the new table. Suppose projects also has a department_id column.
SELECT staff_name, department_name, project_name
FROM staff
INNER JOIN departments USING (department_id)
INNER JOIN projects USING (department_id);This works because the merged department_id from the first join is available to the second. Problems start when a column name appears in three or more tables with different meanings. A name like id or name that exists in all of them either causes an ambiguity error or joins on a column you did not intend. Once the key names differ between tables, switch that join to ON. Mixing USING and ON in one query is allowed.
NATURAL JOIN
NATURAL JOIN takes no condition at all. The database finds every column name that appears in both tables and joins on all of them with equality.
SELECT staff_name, department_name
FROM staff
NATURAL JOIN departments;Today the only shared column is department_id, so the result matches the earlier queries. A bare NATURAL JOIN is an inner join by default. The INNER keyword is optional and rarely written.
Why it is risky
The join condition depends on the current column names, not on anything written in the query. A schema change can alter the result without anyone touching the query. Suppose a migration adds an audit column to both tables.
ALTER TABLE staff ADD COLUMN created_at DATE;
ALTER TABLE departments ADD COLUMN created_at DATE;
SELECT staff_name, department_name
FROM staff
NATURAL JOIN departments;The same query now also requires staff.created_at = departments.created_at. The new columns are all NULL, so no pair is equal and the query returns zero rows. No error is raised. If the new column held real dates, the query would silently drop every pair whose dates differ.
Other drawbacks:
- A reader must know both tables' full column lists to know what the join does.
- Renaming a column in one table can break or change the join.
- Columns named
id,name,created_atorupdated_atcollide constantly, so the shared set is rarely what you meant.
Choosing between ON, USING and NATURAL
| Form | You write | Condition types | Output columns | Main risk |
|---|---|---|---|---|
| `ON` | The full condition | Any, including ranges and extra predicates | Both columns kept | More typing |
| `USING (...)` | Shared column names | Equality only | Shared columns merged | Names must match; portability |
| `NATURAL JOIN` | Nothing | Equality on all shared names | Shared columns merged | Silent change when columns are added |
A practical rule: use ON as the default, use USING when the names match and the query benefits from the shorter form or the merged column, and treat NATURAL JOIN as something to recognize when reading old code, not to write.
Summary of behavior to remember
USINGandNATURAL JOINare still inner joins. Unmatched rows and rows withNULLkeys are excluded.- Both merge the joined columns into one output column.
- Both depend on identical column names, so a naming convention such as
department_ideverywhere makesUSINGpractical. - When the condition needs different names, ranges, or additional predicates, use
ON.
Exercise
Rewrite this query with USING, then say what SELECT * returns for the departmentid column compared with the ON version. SELECT s.staffname, d.departmentname FROM staff AS s INNER JOIN departments AS d ON d.departmentid = s.department_id;
Show answer
SELECT staffname, departmentname FROM staff INNER JOIN departments USING (departmentid); With SELECT *, the USING version returns departmentid once (merged, listed first in PostgreSQL and MySQL), while the ON version returns it twice, once from each table.
Exercise
A teammate adds an updated_at column to both staff and departments. A report written as staff NATURAL JOIN departments now returns fewer rows than before, with no error. Explain why, and name the safer rewrite.
Show answer
NATURAL JOIN joins on every column name the two tables share, so after the change it requires departmentid and updatedat to be equal. Pairs whose updatedat values differ, or are NULL, no longer match, so rows vanish. Rewriting with INNER JOIN ... USING (departmentid) or ON d.departmentid = s.departmentid fixes the join condition regardless of later column additions.