PostgreSQL NATURAL JOIN
Summary: in this tutorial, you will learn how to use the PostgreSQL NATURAL JOIN
to query data from two tables.
Introduction to PostgreSQL NATURAL JOIN clause
A natural join is a join that creates an implicit join based on the same column names in the joined tables.
The following shows the syntax of the PostgreSQL NATURAL JOIN clause:
In this syntax:
- First, specify columns from the tables from which you want to retrieve data in the
select_list
in theSELECT
clause. - Second, provide the main table (
table1
) from which you want to retrieve data. - Third, specify the table (
table2
) that you want to join with the main table, in theNATURAL JOIN
clause.
A natural join can be an inner join, left join, or right join. If you do not specify an explicit join, PostgreSQL will use the INNER JOIN
by default.
The convenience of the NATURAL JOIN
is that it does not require you to specify the condition in the join clause because it uses an implicit condition based on the equality of the common columns.
The equivalent of the NATURAL JOIN
clause will be like this:
Inner Join
The following statements are equivalent:
And
Left Join
The following statements are equivalent:
And
Right join
The following statements are equivalent:
And
Setting up sample tables
The following statements create categories
and products
tables, and insert sample data for the demonstration:
The products
table has the following data:
The categories
table has the following data:
PostgreSQL NATURAL JOIN examples
Let’s explore some examples of using the NATURAL JOIN
statement.
1) Basic PostgreSQL NATURAL JOIN example
The following statement uses the NATURAL JOIN
clause to join the products
table with the categories
table:
This statement performs an inner join using the category_id
column.
Output:
The statement is equivalent to the following statement that uses the INNER JOIN
clause:
2) Using PostgreSQL NATURAL JOIN to perform a LEFT JOIN
The following example uses the NATURAL JOIN
clause to perform a LEFT JOIN
without specifying the matching column:
Output:
3) Example of using NATURAL JOIN that causes an unexpected result
In practice, you should avoid using the NATURAL JOIN
whenever possible because sometimes it may cause an unexpected result.
Consider the following city
and country
tables from the sample database:
Both tables have the same country_id
column so you can use the NATURAL JOIN
to join these tables as follows:
The query returns an empty result set.
The reason is that both tables have another common column called last_update
. When the NATURAL JOIN
clause uses the last_update
column, it does not find any matches.
Summary
- Use the PostgreSQL
NATURAL JOIN
clause to query data from two or more tables that have common columns.