SQL Right Join

The RIGHT JOIN keyword in SQL is used to retrieve rows from two or more tables. It returns all rows from the right table and the matched rows from the left table. If there is no match, the result is NULL on the side of the left table.

Syntax

The basic syntax for a RIGHT JOIN is:


SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;

        

Example

Consider two tables: Customers and Orders. To retrieve a list of all orders along with the customer who placed them, including orders that do not have a corresponding customer, you can use the following query:


SELECT Orders.order_id, Customers.name
FROM Orders
RIGHT JOIN Customers
ON Orders.customer_id = Customers.id;

        

Explanation

  • SELECT columns: Specifies the columns to retrieve from the tables.
  • FROM table1: Indicates the primary (left) table from which to retrieve data.
  • RIGHT JOIN table2: Specifies the secondary (right) table to join with the left table.
  • ON table1.column = table2.column: Defines the condition for the join, i.e., the common column between the two tables.