SQL RIGHT JOIN

SQL RIGHT JOIN is a type of join operation in Structured Query Language (SQL) used to combine data from two or more tables based on the values of the right table. The right join returns all the rows from the right table (also called the right-side table), and the matching rows from the left table (also called the left-side table). If there's no match, the result will contain NULL values for the columns from the left table.

Consider the following two tables:

Orders Table:

OrderIDCustomerID
110
220
330
440

Customers Table:

CustomerIDCustomerName
10William
20Alice
30Bob

Suppose we want to retrieve all the customers along with their order details, and for customers who have no orders, we want to see their names with a NULL value for the OrderID. In that case, we can use the RIGHT JOIN to combine the data from the Orders and Customers tables as follows:

1SELECT * 2FROM Orders 3RIGHT JOIN Customers 4ON Orders.CustomerID = Customers.CustomerID;

The output of the above query will be:

OrderIDCustomerIDCustomerName
110William
220Alice
330Bob
NULL40NULL

As we can see from the output, the RIGHT JOIN returns all the rows from the Customers table, and the matching rows from the Orders table. For the customer with ID 40, there's no matching row in the Orders table, so the result contains NULL values for the OrderID and CustomerName columns from the Orders table.