postgresql
  1. postgresql-right-join

Right Join - (PostgreSQL Join)

In PostgreSQL, a join is used to combine rows from two or more tables based on a related column between them. A right join returns all the rows from the right table and matching rows from the left table. In this tutorial, we'll explore the syntax, example, output, explanation, use, important points, and summary of the right join in PostgreSQL.

Syntax

SELECT column_name(s)
FROM right_table
RIGHT JOIN left_table
ON right_table.column_name = left_table.column_name;

Example

Let's consider the following two tables employees and departments:

employees table:

id name department_id
1 John 1
2 Jane 2
3 Alex 3
4 Michael 2
5 Christopher NULL

departments table:

id name
1 Sales
2 Marketing
3 Operations

Now, let's perform a right join on these two tables to get all the rows from the departments table and matching rows from the employees table:

SELECT *
FROM departments
RIGHT JOIN employees
ON departments.id = employees.department_id;

The above query will return the following result:

id name id name department_id
1 Sales 1 John 1
2 Marketing 2 Jane 2
2 Marketing 4 Michael 2
3 Operations 3 Alex 3
NULL NULL 5 Christopher NULL

Explanation

In the above example, we performed a right join on the departments and employees tables based on the id and department_id columns respectively.

The SELECT statement returns all columns from both tables where there is a match between departments.id and employees.department_id, and also returns the unmatched departments rows. In the final result set, the unmatched rows from the left table (departments table) have NULL values in the corresponding columns from the right table (employees table).

Use

The right join is useful in cases where you want to return all the rows from the right table, even if there are no matching rows in the left table. By including the unmatched rows from the left table in the result set, you can get a better understanding of the data in both tables.

Important Points

  • In a right join, all the rows from the right table are returned, even if there are no matching rows in the left table.
  • The result table of the right join operation will have NULL values for the columns related to the unmatched rows from the left table.
  • It is important to use the same data type for the columns used in the join condition.

Summary

In this tutorial, we discussed the right join operation in PostgreSQL. We covered the syntax, example, output, explanation, use, and important points of the right join in PostgreSQL. With this knowledge, you can now use the right join operation in PostgreSQL to combine data from two or more tables based on a related column.

Published on: