In SQL, LEFT JOIN and RIGHT JOIN are types of outer joins that allow you to retrieve data from two or more tables and include records that do not have a match in one of the tables. The primary difference between the two is which table's rows are prioritized when there are no matches.
LEFT JOIN (or LEFT OUTER JOIN)
A LEFT JOIN returns all records from the left table and the matched records from the right table. If there is no match, the result is NULL on the side of the right table.
Syntax
SELECT columns
FROM table1
LEFT JOIN table2 ON table1.common_column = table2.common_column;
Example
Using the same employees and departments tables as before, the following SQL query retrieves all employees and their department names, including employees who are not assigned to any department.
SELECT e.name, d.department_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id;
Result Set
| name | department_name |
|---|
| Alice | HR |
| Bob | Engineering |
| Charlie | Marketing |
| David | HR |
| Eve | NULL |
In this example, if employee Eve does not have a department_id, she will still appear in the result with a NULL value for department_name.
RIGHT JOIN (or RIGHT OUTER JOIN)
A RIGHT JOIN returns all records from the right table and the matched records from the left table. If there's no match, the result is NULL on the side of the left table.
Syntax
SELECT columns
FROM table1
RIGHT JOIN table2 ON table1.common_column = table2.common_column;
Example
Continuing with the same tables, you might want to retrieve all department names including those departments that have no employees.
SELECT e.name, d.department_name
FROM employees e
RIGHT JOIN departments d ON e.department_id = d.department_id;
Result Set
| name | department_name |
|---|
| Alice | HR |
| David | HR |
| Bob | Engineering |
| Charlie | Marketing |
| NULL | Sales |
In this case, if there is a department called "Sales" that does not have any employees, it will still be included in the result set, but with a NULL value for the name column.
Summary
- LEFT JOIN: Includes all records from the left table and the matched records from the right table; if there's no match, NULLs are returned for the right table's columns.
- RIGHT JOIN: Includes all records from the right table and the matched records from the left table; if there's no match, NULLs are returned for the left table's columns.
Both types of joins are useful depending on the requirements of your query and which dataset you want to prioritize.