Challenge - 5 Problems
Self JOIN Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of a Self JOIN Query
Given the table Employees 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;
MySQL
CREATE TABLE Employees (id INT, name VARCHAR(50), manager_id INT); INSERT INTO Employees VALUES (1, 'Alice', NULL), (2, 'Bob', 1), (3, 'Charlie', 1), (4, 'David', 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;
Attempts:
2 left
💡 Hint
Think about how the
manager_id links to the id in the same table.✗ Incorrect
The query joins the Employees table to itself to find each employee's manager name. If
manager_id is NULL, the manager name is NULL. Otherwise, it matches the manager's id to get the manager's name.📝 Syntax
intermediate1:30remaining
Identify the Syntax Error in Self JOIN
Which option contains a syntax error in this self JOIN query?
SELECT e.name, m.name FROM Employees e JOIN Employees m ON e.manager_id = m.id;
Attempts:
2 left
💡 Hint
Check the ORDER BY clause syntax carefully.
✗ Incorrect
Option B has an incomplete ORDER BY clause without specifying any column, causing a syntax error.
❓ optimization
advanced2:30remaining
Optimizing a Self JOIN Query for Performance
You have a large Employees table with millions of rows. Which option will improve the performance of this self JOIN query the most?
SELECT e.name, m.name FROM Employees e JOIN Employees m ON e.manager_id = m.id WHERE e.department = 'Sales';
Attempts:
2 left
💡 Hint
Think about which columns are used in JOIN and WHERE clauses.
✗ Incorrect
Indexes on the columns used in JOIN and WHERE conditions speed up lookups and filtering, improving query performance.
🔧 Debug
advanced2:00remaining
Debugging Unexpected NULLs in Self JOIN Result
A query returns NULL for all manager names even though managers exist. Which option explains the most likely cause?
SELECT e.name, m.name AS Manager FROM Employees e LEFT JOIN Employees m ON e.manager_id = m.id;
Attempts:
2 left
💡 Hint
Check if the join condition matches any rows.
✗ Incorrect
If
manager_id values do not correspond to any id in the table, the LEFT JOIN returns NULL for manager columns.🧠 Conceptual
expert3:00remaining
Understanding Recursive Relationships with Self JOIN
Consider an Employees table where each employee can have a manager, and managers can also have managers, forming a hierarchy. Which SQL approach best retrieves the full management chain for a given employee in MySQL 8+?
Attempts:
2 left
💡 Hint
Think about how to handle an unknown number of management levels.
✗ Incorrect
Recursive CTEs allow querying hierarchical data by repeatedly joining the table to itself until all levels are retrieved.