Welcome to our comprehensive guide on SQL RIGHT JOIN! In this lesson, we'll dive deep into understanding the concept of RIGHT JOIN, its usage, and examples. By the end of this tutorial, you'll be able to confidently apply RIGHT JOIN in your SQL queries.
A RIGHT JOIN, also known as a derived right outer join, is a type of SQL join that returns all records from the right table (the table listed after the JOIN keyword) and the matching records from the left table (the table listed before the JOIN keyword). If there is no match, the result is NULL from the left side.
Let's illustrate this with an example:
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
RIGHT JOIN Customers
ON Orders.CustomerID = Customers.CustomerID;In this example, we're joining the Orders and Customers tables on the CustomerID field. The RIGHT JOIN ensures that we get all orders, along with the customer name, even if there are customers without any orders.
The SQL RIGHT JOIN syntax is as follows:
SELECT [columns]
FROM left_table
RIGHT JOIN right_table
ON common_field;Let's consider two tables, Orders and Customers.
CREATE TABLE Customers (
CustomerID INT,
CustomerName VARCHAR(50)
);
CREATE TABLE Orders (
OrderID INT,
CustomerID INT,
OrderDate DATE
);Insert some data into the tables:
INSERT INTO Customers (CustomerID, CustomerName)
VALUES (1, 'John Doe'), (2, 'Jane Smith'), (3, NULL);
INSERT INTO Orders (OrderID, CustomerID, OrderDate)
VALUES (1, 1, '2022-01-01'), (2, 1, '2022-02-01'), (3, NULL, '2022-03-01');Now, let's run a RIGHT JOIN query:
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
RIGHT JOIN Customers
ON Orders.CustomerID = Customers.CustomerID;This will result in:
| OrderID | CustomerName |
|---------|--------------|
| 1 | John Doe |
| 2 | John Doe |
| 3 | NULL |
As you can see, we got all the orders (OrderID 1 and 2) along with their corresponding customer names (John Doe), and an order (OrderID 3) without a matching customer, which is represented by NULL.
The main difference between RIGHT OUTER JOIN and LEFT OUTER JOIN is the order of the tables in the query and the side from which NULL values are returned when there is no match.
In a RIGHT OUTER JOIN, NULL values come from the left side when there's no match, while in a LEFT OUTER JOIN, NULL values come from the right side.
What does a SQL RIGHT JOIN return?