SQL RIGHT JOIN
The SQL RIGHT JOIN clause is used to retrieve all rows from the right table (the second table in the JOIN), and the matching rows from the left table. If there is no match, the result is NULL on the side of the left table.
This join is useful when you want to retain all records from the right table, even if there are no corresponding records in the left table.
Tables Used
Orders Table:OrderID | Product | CustomerID |
---|---|---|
1 | Laptop | 101 |
2 | Phone | 102 |
3 | Tablet | NULL |
CustomerID | CustomerName |
---|---|
101 | Alice |
102 | Bob |
103 | Charlie |
Example
We’ll perform a RIGHT JOIN to include all rows from the Customers table, even if there is no match in the Orders table.
Code Example
-- Perform a RIGHT JOIN between Orders and Customers
SELECT Orders.OrderID, Orders.Product, Customers.CustomerName
FROM Orders
RIGHT JOIN Customers
ON Orders.CustomerID = Customers.CustomerID;
-- View the resulting table
Output Table
OrderID | Product | CustomerName |
---|---|---|
1 | Laptop | Alice |
2 | Phone | Bob |
NULL | NULL | Charlie |
Explanation
- The RIGHT JOIN ensures all rows from the Customers table are included.
- For rows without a match in the Orders table, the OrderID and Product columns are NULL.