Beruflich Dokumente
Kultur Dokumente
1 di 4
http://www.postgresqltutorial.com/postgresql-natural-join/
Summary: in this tutorial, you will learn how to use the PostgresQL NATURAL JOIN to query data
from two or more tables.
A natural join is a join that creates an implicit join based on the same column names in the joined
tables. See the following syntax of PostgreSQL natural join:
1 SELECT *
2 FROM T1
3 NATURAL [INNER, LEFT, RIGHT] JOIN T2
A natural join can be an inner join, left join, or right join. If you do not specify a join explicitly e.g.,
INNER JOIN , LEFT JOIN , RIGHT JOIN , PostgreSQL will use the INNER JOIN by default.
If you use the asterisk (*) in the select list, the result will contain the following columns:
All the common columns, which are the columns in the both tables that have the same name
Every column in the rst and second tables that is not a common column
13/12/2016 16.04
2 di 4
10
http://www.postgresqltutorial.com/postgresql-natural-join/
11 )
Each category has zero or many products whereas each product belongs to one and only one
category. The category_id column in the products table is the foreign key that references to
the primary key of the categories table. The category_id is the common column that we will
use to perform the natural join.
The following INSERT statements insert some sample data into the categories and products
tables.
1
VALUES
('Smart Phone'),
('Laptop'),
('Tablet')
VALUES
('iPhone', 1),
10
11
12
13
('iPad', 3),
14
('Kindle Fire', 3)
The following statement uses the NATURAL JOIN clause to join the products table with the
categories table:
1 SELECT
2
3 FROM
4
products
3 di 4
http://www.postgresqltutorial.com/postgresql-natural-join/
The above statement is equivalent to the following statement that uses the INNER JOIN clause.
1 SELECT
2
3 FROM
4
products
The convenience of the NATURAL JOIN is that it does not require you to specify the join clause
because it uses an implicit join clause based on the common column.
However, you should avoid using the NATURAL JOIN whenever possible because sometimes it
may cause an unexpected result.
For example, lets take a look at the city and country tables. Both tables have the same
country_id column so we can use the NATURAL JOIN to join these tables as follows:
1 SELECT
2
3 FROM
4
city
2 ------------+-------------+---------+------+--------3 (0 rows)
In this tutorial, we have explained to you how the PostgreSQL NATURAL JOIN works and 13/12/2016
shown 16.04
4 di 4
http://www.postgresqltutorial.com/postgresql-natural-join/
In this tutorial, we have explained to you how the PostgreSQL NATURAL JOIN works and shown
you how to use it to query data from two or more tables.
Related Tutorials
PostgreSQL INNER JOIN
PostgreSQL LEFT JOIN
PostgreSQL Cross Join By Example
PostgreSQL FULL OUTER JOIN
13/12/2016 16.04