You have two tables: Employees and Departments. You want to list all employees and their departments, including employees who are not assigned to any department.
Which JOIN type should you use?
Think about which table you want to keep all rows from.
LEFT JOIN keeps all rows from the left table (Employees) and matches rows from the right table (Departments). This shows all employees, even those without a department.
Given these tables:
Employees: (id, name) 1, Alice 2, Bob 3, Carol Departments: (id, dept_name) 2, Sales 3, HR 4, IT
What is the result of this query?
SELECT Employees.name, Departments.dept_name FROM Employees LEFT JOIN Departments ON Employees.id = Departments.id;
LEFT JOIN keeps all rows from Employees and matches Departments where IDs are equal.
Alice has no matching department so dept_name is null. Bob and Carol match Sales and HR respectively. IT department is not included because no employee has id 4.
Which option contains a syntax error in this RIGHT JOIN query?
SELECT e.name, d.dept_name FROM Employees e RIGHT JOIN Departments d ON e.id = d.id;
Check the placement of the ON clause in JOIN syntax.
Option C uses WHERE instead of ON for the join condition, causing a syntax error.
You want to optimize a query that lists all departments and their employees, including departments with no employees. Which join is generally more efficient?
Think about which table you want to keep all rows from and typical indexing.
LEFT JOIN starting from Departments keeps all departments and matches employees. It is usually more efficient because the driving table is the one with fewer rows or the one you want to keep all rows from.
You run this query:
SELECT e.name, d.dept_name FROM Employees e RIGHT JOIN Departments d ON e.id = d.id;
But you see NULLs in e.name for some rows unexpectedly. What is the most likely cause?
Think about what RIGHT JOIN does and when NULLs appear.
RIGHT JOIN keeps all rows from Departments. If a department has no matching employee, employee columns show NULL.