Given the employees table with columns id, name, and manager_id (which references id of the manager), what is the output of the following query?
SELECT e.name AS employee, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id ORDER BY e.id;
CREATE TABLE employees (id INT PRIMARY KEY, name TEXT, manager_id INT); INSERT INTO employees VALUES (1, 'Alice', NULL), (2, 'Bob', 1), (3, 'Charlie', 1), (4, 'Diana', 2); SELECT e.name AS employee, m.name AS manager FROM employees e LEFT JOIN employees m ON e.manager_id = m.id ORDER BY e.id;
Think about how the manager_id links to the id of the manager in the same table.
The query joins the employees table to itself to find each employee's manager by matching manager_id to id. Alice has no manager, so manager is null. Bob and Charlie report to Alice, and Diana reports to Bob.
Which option contains a syntax error in this self join query to find pairs of employees who share the same manager?
SELECT e1.name, e2.name FROM employees e1 JOIN employees e2 ON e1.manager_id = e2.manager_id WHERE e1.id != e2.id;
Check if the JOIN clause has a proper ON condition.
Option A is missing the ON keyword after JOIN employees e2, which causes a syntax error. The WHERE clause cannot replace the ON condition in an explicit JOIN.
You want to find all employees and their direct managers from a large employees table. Which query is more efficient?
Consider the difference between LEFT JOIN and JOIN and the impact on rows returned.
Option D uses a LEFT JOIN to include employees without managers (e.g., top-level). It is efficient and returns all employees. Option D uses a correlated subquery which can be slower on large tables. Option D excludes employees without managers. Option D uses CROSS JOIN with a WHERE filter, which is less efficient.
Which statement best describes how recursive self joins help in querying hierarchical data?
Think about how you can find all subordinates under a manager at any depth.
Recursive self joins (often implemented with recursive CTEs) join a table to itself repeatedly to walk down or up a hierarchy until all levels are processed.
Given the employees table with id, name, and manager_id, a query attempts to list employees and their managers but returns duplicate rows for some employees. Which option explains the cause?
SELECT e.name AS employee, m.name AS manager FROM employees e JOIN employees m ON e.manager_id = m.id JOIN employees d ON d.manager_id = m.id WHERE d.name = 'Diana';
Consider how joining the same table multiple times can multiply rows.
The join to d finds all employees managed by the same manager as e. If a manager has multiple subordinates, this join multiplies rows for each combination, causing duplicates.