MySQL RIGHT JOIN Keyword

The RIGHT JOIN keyword in MySQL is used to return all records from the right table (table2), and the matching records (if any) from the left table (table1). If there is no match, the result will still include all records from the right table, with NULL values for the columns from the left table.

RIGHT JOIN Syntax

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
  • table1: The left table from which only the matching records are returned.
  • table2: The right table from which all records are returned.
  • column_name: The columns used to establish the join condition.

How RIGHT JOIN Works

  • The RIGHT JOIN ensures that all rows from the right table (table2) will be included in the result set.
  • If there are matching rows in the left table (table1), those will also be included.
  • If there are no matching rows in the left table, the result will include NULL values for columns from table1.

Example:

SELECT Employees.EmployeeID, Orders.OrderID
FROM Employees
RIGHT JOIN Orders ON Employees.EmployeeID = Orders.EmployeeID;
  • This query will return all records from the Orders table, with matching records from the Employees table. If an order doesn't have an employee assigned (no match), the EmployeeID from the Employees table will be NULL.

Key Points:

  • RIGHT JOIN is the opposite of LEFT JOIN.
  • It includes all records from the right table, even if there is no matching record in the left table.
  • It's especially useful when you want to ensure that all records from the right table are returned, regardless of whether a match exists in the left table.

Was this article helpful?