sql
  1. sql-right-join

SQL RIGHT JOIN

The SQL RIGHT JOIN is used to retrieve all the rows from the right table and the matching rows from the left table. If there are no matches, the result will include null values.

Syntax

SELECT
    column_1,
    column_2,
    ...
FROM
    table_right
RIGHT JOIN table_left
ON table_right.column = table_left.column;

Example

Consider two tables, customers and orders.

The customers table:

id name age
1 John 28
2 Mary 32
3 Michael 25
4 Jessica 29

The orders table:

id customer_id product quantity
1 2 iPhone 2
2 1 iPad 1
3 2 Headset 1
4 3 MacBook 3

We can perform a right join on these two tables using the following query:

SELECT
    customers.name,
    orders.product,
    orders.quantity
FROM
    orders
RIGHT JOIN customers
ON orders.customer_id = customers.id;

The output of this query will be:

name product quantity
John iPad 1
Mary iPhone 2
Mary Headset 1
Michael NULL NULL
Jessica NULL NULL

Explanation

This query uses a right join to combine the customers and orders tables. The join condition is specified using the ON keyword, which specifies that the customer_id column in the orders table should match the id column in the customers table.

Since the RIGHT JOIN will include all the rows from the orders table, even those with no corresponding rows in the customers table, the output will include NULL values for the name column and quantity column for Michael and Jessica.

Use

The SQL RIGHT JOIN can be used to retrieve all the rows from the right table and the matching rows from the left table. This is useful when we want to include all the data from the right table in our output, even if there are no matching rows in the left table.

Important Points

  • The SQL RIGHT JOIN is used to retrieve all the rows from the right table and the matching rows from the left table.
  • If there are no matches, the result will include null values.
  • The join condition is specified using the ON keyword.
  • The output includes all the rows from the right table and the matching rows from the left table.

Summary

The SQL RIGHT JOIN is used to retrieve all the rows from the right table and the matching rows from the left table, including rows with no matches. The join condition is specified using the ON keyword, and the output includes all the rows from the right table and the matching rows from the left table.

Published on: