SQL Right Join
In SQL, a RIGHT JOIN
is used to retrieve all records from the right table and the matching records from the left table based on a specified condition. It returns all the rows from the right table and only the matching rows from the left table. If there is no match, NULL values are returned for the columns of the left table.
The syntax for a RIGHT JOIN
is as follows:
sql
SELECT column_list
FROM table1
RIGHT JOIN table2 ON join_condition;
Here, table1
is the left table, table2
is the right table, and join_condition
specifies the condition for joining the tables. The column_list
represents the columns you want to retrieve from the resulting joined table.
Let’s consider an example to illustrate the usage of a RIGHT JOIN
:
Suppose we have two tables, “Customers” and “Orders,” with the following structures and data:
Customers table:
CustomerID | CustomerName |
---|---|
1 | John |
2 | Emma |
3 | Mike |
Orders table:
OrderID | CustomerID | OrderDate |
---|---|---|
1 | 1 | 2023-06-01 |
2 | 3 | 2023-06-02 |
3 | 2 | 2023-06-03 |
4 | 1 | 2023-06-04 |
To retrieve all customers and their corresponding orders (if any), we can use a RIGHT JOIN
:
sql
SELECT Customers.CustomerName, Orders.OrderID, Orders.OrderDate
FROM Customers
RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
The result of the above query will be:
CustomerName | OrderID | OrderDate |
---|---|---|
John | 1 | 2023-06-01 |
Mike | 2 | 2023-06-02 |
Emma | 3 | 2023-06-03 |
John | 4 | 2023-06-04 |
As you can see, the RIGHT JOIN
returns all the rows from the “Orders” table and only the matching rows from the “Customers” table. In this case, all the orders are included, and customers without orders are also included with NULL values in the “CustomerName” column.