Bird
0
0

Given the employees table:

medium📝 query result Q4 of 15
SQL - Advanced Joins
Given the employees table:
id | name    | manager_id
---+---------+-----------
1  | Alice   | NULL
2  | Bob     | 1
3  | Charlie | 1
4  | David   | 2
What will be the output of this 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;
A[{"Employee": "Alice", "Manager": "Bob"}, {"Employee": "Bob", "Manager": "Charlie"}, {"Employee": "Charlie", "Manager": "David"}, {"Employee": "David", "Manager": null}]
B[{"Employee": "Alice", "Manager": null}, {"Employee": "Bob", "Manager": "Alice"}, {"Employee": "Charlie", "Manager": "Alice"}, {"Employee": "David", "Manager": "Bob"}]
C[{"Employee": "Alice", "Manager": "Alice"}, {"Employee": "Bob", "Manager": "Bob"}, {"Employee": "Charlie", "Manager": "Charlie"}, {"Employee": "David", "Manager": "David"}]
D[{"Employee": "Alice", "Manager": null}, {"Employee": "Bob", "Manager": null}, {"Employee": "Charlie", "Manager": null}, {"Employee": "David", "Manager": null}]
Step-by-Step Solution
Solution:
  1. Step 1: Understand LEFT JOIN with self join

    Each employee is matched with their manager by matching e.manager_id to m.id. If no manager (NULL), manager name is NULL.
  2. Step 2: Map employees to managers

    Alice has no manager (NULL), Bob and Charlie have Alice as manager (id 1), David has Bob as manager (id 2).
  3. Final Answer:

    [{"Employee": "Alice", "Manager": null}, {"Employee": "Bob", "Manager": "Alice"}, {"Employee": "Charlie", "Manager": "Alice"}, {"Employee": "David", "Manager": "Bob"}] -> Option B
  4. Quick Check:

    Self join output matches hierarchy [OK]
Quick Trick: LEFT JOIN shows NULL for top-level with no manager [OK]
Common Mistakes:
MISTAKES
  • Assuming manager name equals employee name
  • Confusing join direction
  • Ignoring NULL manager cases

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes