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:
OrderID | CustomerID |
---|---|
1 | 10 |
2 | 20 |
3 | 30 |
4 | 40 |
Customers Table:
CustomerID | CustomerName |
---|---|
10 | William |
20 | Alice |
30 | Bob |
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:
OrderID | CustomerID | CustomerName |
---|---|---|
1 | 10 | William |
2 | 20 | Alice |
3 | 30 | Bob |
NULL | 40 | NULL |
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.