SQL RIGHT JOIN Keyword

The RIGHT JOIN keyword in SQL is used to combine 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 is particularly useful when you want to see all the data from the right-hand table, even if there are no matches in the left-hand table. For rows in the right-hand table without a match in the left-hand table, the columns from the left-hand table will contain 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

Joining Orders and Employees

This example uses a RIGHT JOIN to retrieve all employees and their corresponding orders. If an employee hasn't placed any orders, their name will still appear in the results, with NULL values for the order-related columns. (Assumes 'Orders' and 'Employees' tables exist with appropriate linking columns.)

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
-------------------------------
(OrderID) | (LastName) | (FirstName)  (All employees will be listed; if an employee has no orders, OrderID will be NULL)

      

**Note:** The example output shows a general structure. The specific employee and order data will depend on the contents of your `Orders` and `Employees` tables. The `(...)` indicates that multiple rows will be returned, including all employees. If an employee has no associated orders, the `OrderID` will be `NULL` for that employee's row.