SQL RIGHT JOIN

What is RIGHT JOIN?

RIGHT JOIN, also known as RIGHT OUTER JOIN, is a type of join that returns all records from the right table (table2) and the matched records from the left table (table1). If there is no match, NULL values are returned for columns from the left table.

Syntax of RIGHT JOIN

SELECT column1, column2, ...
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;

In this syntax, table2 is the right table, and table1 is the left table. The join is performed based on the specified column_name.

RIGHT JOIN Example

Here’s an example of using RIGHT JOIN to retrieve data from two related tables:

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

This query selects the CustomerName from the Customers table and the OrderID from the Orders table. If an order does not have a matching customer, the CustomerName will be NULL.

Use Cases of RIGHT JOIN

RIGHT JOIN is useful in various scenarios, such as:

  • Retrieving all records from a secondary table while showing related data from a primary table, even if no matches exist.
  • Finding records in the right table that do not have corresponding entries in the left table.
  • Generating reports that include all transactions, including those that do not have a customer associated.

Practice Exercise

Write your own RIGHT JOIN queries using example tables like Customers and Orders. Try to include different columns in your SELECT statement!