How to Join Tables Using USING Instead of ON
The idea of joining tables is built on simplification and reducing row duplication. If you don't know how to use ON to join tables, check out this topic—it will help you: For Those Who Do Not Know JOIN
- USING
- ON
- shared column
- JOIN
Introduction
The idea of joining tables is built on simplification and reducing row duplication. If you don't know how to use ON to join tables, check out this topic—it will help you: For Those Who Do Not Know JOIN
Example
Suppose we have a countries table:
code | name
-----|---------------------
EGY | Egypt
KSA | Saudi Arabia
UAE | United Arab EmiratesAnd a cities table:
id | code | name
---|------|-----------------
1 | EGY | Cairo
2 | UAE | Dubai
3 | KSA | JeddahOf course, to join tables, we must know the primary key and the foreign key.
Notice that what links the two tables is a column named code. So the primary key is the code column in the countries table, and the foreign key is the code column in the cities table.
So we write:
SELECT *
FROM countries
JOIN cities
ON countries.code = cities.codeIf we use USING, we will find the process is simpler than that.
If we want to retrieve the country name and city name after joining the two tables, we write:
SELECT c1.name AS country, c2.name AS city
FROM countries AS c1
JOIN cities AS c2
USING (code)Notice that I wrote the key name inside parentheses after the USING keyword. The join will happen the exact same way and produce the same output:
country | city
---------------------|--------
Egypt | Cairo
Saudi Arabia | Jeddah
United Arab Emirates | DubaiWhat if the primary key column name is different from the foreign key column name?
The general syntax would be:
USING (first_join_column_name, second_join_column_name)That is, you write the primary key name and the foreign key name inside parentheses after USING and separate them with a comma. (Note: In standard SQL/PostgreSQL, USING requires both tables to share the same column name.)