Self Joins & Hierarchical Queries SQL Topic exerciseEasyVerified answerSQLite + PostgreSQL + MySQL + SQL Server live · 1 guided

Find Employee Manager Details Using Self Join

Display each employee along with their manager's name using a self-join. Top-level employees (manager_id IS NULL) must still appear with manager_name = NULL. Return employee_id, employee_name, manager_id, manager_name — ordered by employee_id.

  • Joins
  • NULL handling
  • Sorting

Exercise brief

Understand the request

People operations analyst The employee directory must preserve executives who have no manager while resolving every valid reporting relationship.

Return

  • Return the four requested employee and manager columns.
  • Order by employee_id.

Constraints

  • Use two aliases of employees.
  • Use LEFT JOIN so root employees remain visible.

Data you will use

Review the relevant tables before deciding how to join, filter, or aggregate them.

employees

  • employee_idINTEGER
  • employee_nameTEXT
  • manager_idINTEGER

Hints, when you need them

Open one clue at a time so you still do the reasoning.

Hint 1

Self-join: alias the same table twice. `e` plays the role of "employee", `m` plays "manager".

Hint 2

Join predicate: e.manager_id = m.employee_id — the employee's manager_id matches some other employee's primary key.

Hint 3

LEFT JOIN keeps the CEO (manager_id IS NULL); INNER JOIN would drop them.

Verified SQL answer

Attempt the problem first, then compare structure and reasoning—not just syntax.

Reveal solution and explanation
SELECT e.employee_id, e.employee_name, e.manager_id, m.employee_name AS manager_name FROM employees e LEFT JOIN employees m ON e.manager_id = m.employee_id ORDER BY e.employee_id;

Why this works

Self-joins are the foundational hierarchy pattern. The same physical table plays two roles (employee + manager); aliases make both addressable. Always LEFT JOIN unless you specifically want to drop top-level rows.

Success check

All 15 employees appear exactly once and the CEO has a NULL manager name.

Expected result

Use this output to verify values, aliases, ordering, and row count.

employee_idemployee_namemanager_idmanager_name
1Alice CEONULLNULL
2Bob VP Sales1Alice CEO
3Carol VP Eng1Alice CEO
4David VP HR1Alice CEO
5Emma Sales Mgr2Bob VP Sales
6Frank Eng Mgr3Carol VP Eng
7Grace HR Mgr4David VP HR
8Henry Sales Rep5Emma Sales Mgr
9Ivy Sales Rep5Emma Sales Mgr
10Jack Engineer6Frank Eng Mgr

Previewing 10 of 15 expected rows. Run the query in the editor to inspect the full result.

Learn the concepts behind this answer

Strengthen your understanding with these targeted learning topics:

Continue practicing

SQL Practice Online

Open the interactive workspace and practice across SQL topics.