SQL RIGHT JOIN Keyword
The RIGHT JOIN
keyword in SQL combines rows from two tables based on a related column. Unlike an INNER JOIN
, which only returns rows with matches in both tables, a RIGHT JOIN
returns all rows from the right-hand table and the matching rows from the left-hand table.
RIGHT JOIN: Definition and Usage
A RIGHT JOIN
(sometimes called a RIGHT OUTER JOIN
) is particularly useful when you need to retrieve all data from the right-hand table, even if those rows don't have a match in the left-hand table. If a row in the right-hand table doesn't have a corresponding match in the left-hand table (based on the join condition), that row is still included in the results, but the columns from the left-hand table will have NULL
values.
Syntax
Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name
ORDER BY column_name;
Example Databases
We'll use excerpts from the 'Orders' and 'Employees' tables (a simplified version of the Northwind database) for the examples below:
Orders Table (Sample Data)
OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
---|---|---|---|---|
10308 | 2 | 7 | 1996-09-18 | 3 |
10309 | 37 | 3 | 1996-09-19 | 1 |
10310 | 77 | 8 | 1996-09-20 | 2 |
Employees Table (Sample Data)
EmployeeID | LastName | FirstName | BirthDate | Photo |
---|---|---|---|---|
1 | Davolio | Nancy | 1968-12-08 | EmpID1.pic |
2 | Fuller | Andrew | 1952-02-19 | EmpID2.pic |
3 | Leverling | Janet | 1963-08-30 | EmpID3.pic |
Example: RIGHT JOIN
This query uses RIGHT JOIN
to get all employees and their orders. Employees without orders will still be listed, with NULL
for `OrderID`.
Syntax
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID;
Output
OrderID | LastName | FirstName
-------------------------------
NULL | Davolio | Nancy
NULL | Fuller | Andrew
10309 | Leverling | Janet
(More rows might appear here depending on your data)