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:
SELECT column_list FROM table1 RIGHT JOIN table2 ON join_condition;
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
Suppose we have two tables, “Customers” and “Orders,” with the following structures and data:
To retrieve all customers and their corresponding orders (if any), we can use a
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:
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.