Sub topic 13
USING and NATURAL JOIN shorthand
Assume you know SELECT, table aliases, primary keys, and foreign keys. You should also know the basic INNER JOIN ... ON ... form. SQL provides two shorthand forms for equality joins: USING and NATURAL JOIN.
`USING` for same-named columns
Use USING (column_name) when both tables contain a join column with exactly the same name. This:
SELECT c.name, o.id AS order_id, o.total
FROM customers AS c
INNER JOIN orders AS o
ON c.id = o.customer_id;cannot use USING, because the columns are named id and customer_id. If the foreign key were also named customer_id in both tables, the equivalent shorthand would be:
SELECT customer_name, order_id, total
FROM customers
INNER JOIN orders
USING (customer_id);USING means equality. It is equivalent to:
ON customers.customer_id = orders.customer_idThe joined column is treated as one column in the result. You can refer to it without qualifying it:
SELECT customer_id, name, order_id
FROM customers
INNER JOIN orders
USING (customer_id);With ON, selecting both matching columns can produce two similarly named output columns. USING avoids that duplicate.
How `USING` changes output
Suppose both tables contain a column called department_id.
| Join form | Join condition | Matching output column |
|---|---|---|
| `ON a.department_id = b.department_id` | Written explicitly | Two source columns may be selected |
| `USING (department_id)` | Equality is implied | One merged `department_id` column |
Use USING when the shared name is intentional and the query is easier to read because of it. Use ON when the names differ, when you need a more complex condition, or when you want the join rule to be immediately explicit.
`NATURAL JOIN`
NATURAL JOIN automatically joins tables using every column name they have in common:
SELECT *
FROM customers
NATURAL JOIN orders;If customers and orders share only customer_id, this behaves like:
SELECT *
FROM customers
INNER JOIN orders
USING (customer_id);The database chooses the join columns from the table definitions. You do not list them yourself.
Why `NATURAL JOIN` is risky
NATURAL JOIN can change meaning when someone adds a column with the same name to either table. For example, if both tables later receive a status column, the natural join may start requiring matching status values as well as matching customer IDs. Existing queries can then return fewer rows without any SQL text changing.
A natural join can be convenient for a quick exploration or a controlled example. It is usually a poor choice for shared application code, reports, and long-lived database views.
Exercise
When should you choose USING instead of NATURAL JOIN?
Show answer
Choose USING when the shared column name and the intended equality condition are known and you want to state that column explicitly. Avoid NATURAL JOIN when schema changes could introduce unintended same-named columns.