PostgreSQL Joins demystified

  • Post comments:0 Comments
  • Reading time:6 mins read
  • Post category:SQL

In this tutorial, we learn about the complete join mechanism in PostgreSQL Joins.

PostgreSQL joins are used to combine columns from one (self-join) or more tables based on the values of the common columns between the tables. The common columns are typically the primary key columns of the first table and foreign key columns of the second table.

PostgreSQL joins

PostgreSQL supports the following join types

  1. inner join
  2. left join
  3. right join
  4. full outer join
  5. cross join
  6. natural join
  7. self join

Let’s discuss each of these join types in detail

Before learning about join types, let’s create two sample tables.

Lets consider android as left table and iphone as right table.

PostgreSQL inner join

Syntax

SELECT
a.id id_android,
a.feature feature_android,
b.id id_iphone,
b.feature feature_iphone
FROM
android a
INNER JOIN iphone b ON a.feature = b.feature;

PS: inner join returns the records that are in common between two tables

PostgreSQL left join

Syntax

SELECT
a.id id_android,
a.feature feature_android,
b.id id_iphone,
b.feature feature_iphone
FROM
android a
LEFT JOIN iphone b ON a.feature = b.feature;

PS: The left join returns a complete set of rows from the left table with the matching rows if available from the right table. If there is no match, the right side will have null values.

We can apply where clause to get only records that are in left table which are not present in right table.

PostgreSQL right join

Right join is complete opposite to left join, it  returns all rows from the right table with matching rows from the left table

PostgreSQL full outer join

Full outer is like a union of both tables. It produces all records in both tables.

PostgreSQL cross join

CROSS JOIN clause allows you to produce the Cartesian Product of rows in two or more tables.

select * from table1 cross join table2;

PostgreSQL Natural Join

A natural join is a join that creates an implicit join based on the same column names in the joined tables.

SELECT *
FROM Table1
NATURAL [INNER, LEFT, RIGHT] JOIN Table2;

PostgreSQL self join

A self-join is a query in which a table is joined to itself. Self-joins are useful for comparing values in a column of rows within the same table. Read here for more about self joins.

 

Words from postgreshelp

Thank you for giving your valuable time to read the above information. I hope the content served your purpose in reaching out the blog.
Suggestions for improvement of the blog are highly appreciable. Please contact us for any information/suggestion/feedback.

If you want to be updated with all our articles

please follow us on Facebook Twitter
Please subscribe to our newsletter.

Leave a Reply