Given two tables, Employees and Departments, what will be the result of the following query?
SELECT Employees.Name, Departments.DepartmentName FROM Employees RIGHT JOIN Departments ON Employees.DepartmentID = Departments.ID;
CREATE TABLE Employees (ID INT, Name VARCHAR(20), DepartmentID INT); INSERT INTO Employees VALUES (1, 'Alice', 10), (2, 'Bob', 20), (3, 'Charlie', NULL); CREATE TABLE Departments (ID INT, DepartmentName VARCHAR(20)); INSERT INTO Departments VALUES (10, 'HR'), (20, 'Engineering'), (30, 'Marketing'); SELECT Employees.Name, Departments.DepartmentName FROM Employees RIGHT JOIN Departments ON Employees.DepartmentID = Departments.ID;
Remember, RIGHT JOIN returns all rows from the right table, and matching rows from the left table.
The RIGHT JOIN returns all departments, even if no employee belongs to them. 'Marketing' has no employee, so employee name is NULL. 'Charlie' has no department, so he is excluded.
Choose the correct description of what a RIGHT JOIN does in SQL.
Think about which table's rows are always included in the result.
RIGHT JOIN returns all rows from the right table, and matching rows from the left table. If no match, left table columns are NULL.
Which option contains a syntax error in the RIGHT JOIN usage?
SELECT e.Name, d.DepartmentName FROM Employees e RIGHT JOIN Departments d ON e.DepartmentID = d.ID;
Check the placement of the ON clause in JOIN syntax.
The ON clause must follow the JOIN keyword directly. Using WHERE instead causes a syntax error.
You have a RIGHT JOIN query joining large tables. Which option is the best way to optimize it?
Think about how databases speed up join operations.
Indexes on join columns help the database find matching rows faster, improving join performance.
Given these tables:
Employees: ID, Name, DepartmentID Departments: ID, DepartmentName
Query:
SELECT e.Name, d.DepartmentName FROM Employees e RIGHT JOIN Departments d ON e.DepartmentID = d.ID WHERE e.Name IS NOT NULL;
Why might this query return fewer rows than a RIGHT JOIN without the WHERE clause?
Consider how WHERE filters rows after the join.
The WHERE clause removes rows where e.Name is NULL, which are the unmatched rows from the right table. This reduces the result set.