SQL Tutorial
The RIGHT JOIN
keyword in SQL returns all records from the right table, and the matched records from the left table. The result is NULL
from the left side, when there is no match.
Here's the basic syntax:
SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;
Consider the following two tables:
Table "Orders"
OrderID | CustomerID | OrderDate |
---|---|---|
1 | 3 | 2023-01-01 |
2 | 1 | 2023-02-01 |
3 | 2 | 2023-03-01 |
Table "Customers"
CustomerID | CustomerName | ContactName | Country |
---|---|---|---|
1 | Alfreds | Maria | Germany |
2 | Ana Trujillo | Ana | Mexico |
3 | Antonio | Antonio | Mexico |
4 | Around the Horn | Thomas | UK |
Let's apply a RIGHT JOIN
with these two tables:
SELECT Orders.OrderID, Customers.CustomerName FROM Orders RIGHT JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
This SQL statement would return:
OrderID | CustomerName |
---|---|
1 | Antonio |
2 | Alfreds |
3 | Ana Trujillo |
NULL | Around the Horn |
This is because the RIGHT JOIN
keyword returns all records from the right table (Customers), and the matched records from the left table (Orders). The result is NULL
from the left side, when there is no match.
Note: Not all database systems support RIGHT JOIN
. However, you can always achieve the same result with a LEFT JOIN
, just swapping the position of the tables. The SQL syntax may vary slightly between different SQL dialects, so always consult the relevant documentation if unsure.
When to Use RIGHT JOIN in SQL:
SELECT * FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;
SQL RIGHT JOIN vs LEFT JOIN:
-- RIGHT JOIN SELECT * FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name; -- LEFT JOIN SELECT * FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name;
Multiple Tables RIGHT JOIN in SQL:
SELECT * FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name RIGHT JOIN table3 ON table2.column_name = table3.column_name;
Common Mistakes with SQL RIGHT JOIN:
-- Mistake: Incorrect order of tables in RIGHT JOIN SELECT * FROM table2 RIGHT JOIN table1 ON table1.column_name = table2.column_name;
Using WHERE Clause with RIGHT JOIN in SQL:
SELECT * FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name WHERE table1.column_name IS NULL;
Nested RIGHT JOIN in SQL:
SELECT * FROM table1 RIGHT JOIN ( table2 RIGHT JOIN table3 ON table2.column_name = table3.column_name ) ON table1.column_name = table2.column_name;
Impact of NULL Values in RIGHT JOIN:
SELECT table1.column1, COALESCE(table2.column2, 'N/A') AS column2 FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;