The LEFT JOIN and RIGHT JOIN are Outer Joins used to combine data from two related tables while preserving all records from one side, even if there are no matches on the other.
NULL values for the missing side.
-- LEFT JOIN: Table1 is the priority
SELECT column1, column2
FROM table1
LEFT JOIN table2
ON table1.id = table2.table1_id;
-- RIGHT JOIN: Table2 is the priority
SELECT column1, column2
FROM table1
RIGHT JOIN table2
ON table1.id = table2.table1_id;
// Fetch all employees even if no department is assigned
SELECT employees.name, departments.dept_name
FROM employees
LEFT JOIN departments
ON employees.dept_id = departments.id;
// Fetch all departments even if they have no employees
SELECT employees.name, departments.dept_name
FROM employees
RIGHT JOIN departments
ON employees.dept_id = departments.id;
Switch between the joins to see how Charlie (No Dept) or Marketing (No Staff) behave.
| Employee Name (Left) | Department Name (Right) |
|---|
LEFT JOIN and simply switching the table order to avoid the confusion of RIGHT JOIN.WHERE table2.id IS NULL with a LEFT JOIN to find records that exist only in the left table.students and courses tables and apply LEFT JOIN.FROM and JOIN clauses.