Bird
0
0

Given table employees(id, name, manager_id) with data:

medium📝 query result Q4 of 15
PostgreSQL - Joins in PostgreSQL
Given table employees(id, name, manager_id) with data:
1 | Alice | NULL
2 | Bob   | 1
3 | Carol | 1
4 | Dave  | 2

What will this query return?
SELECT e1.name AS employee, e2.name AS manager FROM employees e1 LEFT JOIN employees e2 ON e1.manager_id = e2.id;
A[{"employee": "Bob", "manager": null}, {"employee": "Dave", "manager": "Carol"}]
B[{"employee": "Alice", "manager": "Alice"}, {"employee": "Bob", "manager": "Bob"}]
C[{"employee": "Alice", "manager": "Bob"}, {"employee": "Carol", "manager": "Dave"}]
D[{"employee": "Alice", "manager": null}, {"employee": "Bob", "manager": "Alice"}, {"employee": "Carol", "manager": "Alice"}, {"employee": "Dave", "manager": "Bob"}]
Step-by-Step Solution
Solution:
  1. Step 1: Understand LEFT JOIN on self join

    Each employee is matched to their manager by matching manager_id to id in the same table.
  2. Step 2: Map employees to managers

    Alice has no manager (NULL), Bob and Carol have Alice as manager, Dave has Bob as manager.
  3. Final Answer:

    [{"employee": "Alice", "manager": null}, {"employee": "Bob", "manager": "Alice"}, {"employee": "Carol", "manager": "Alice"}, {"employee": "Dave", "manager": "Bob"}] -> Option D
  4. Quick Check:

    Self join LEFT JOIN output = [{"employee": "Alice", "manager": null}, {"employee": "Bob", "manager": "Alice"}, {"employee": "Carol", "manager": "Alice"}, {"employee": "Dave", "manager": "Bob"}] [OK]
Quick Trick: LEFT JOIN keeps all employees, shows NULL if no manager [OK]
Common Mistakes:
  • Assuming manager name is employee name
  • Confusing LEFT JOIN with INNER JOIN
  • Ignoring NULL managers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes