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

Direct Manager and Skip-Level Manager

For each employee show both the direct manager and the skip-level manager (manager's manager). Use two LEFT JOINs so employees without managers (or without skip-level managers) still appear with NULLs. Return employee_id, employee_name, direct_manager_name, skip_level_manager_name — ordered by employee_id.

  • Joins
  • Sorting

Exercise brief

Understand the request

Succession planning lead A leadership pipeline report needs both the direct and skip-level manager while retaining incomplete chains.

Return

  • Return employee identity plus direct and skip-level manager names.
  • Order by employee_id.

Constraints

  • Join employees to itself twice.
  • Use LEFT JOIN for both hierarchy levels.

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

Chain two self-joins: first to direct manager, then to direct-manager's manager.

Hint 2

Keep both as LEFT JOINs — the CEO has no manager, VPs have no skip-level manager.

Hint 3

This is the static-depth alternative to a recursive CTE (Q6) when you know the depth in advance.

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, m1.employee_name AS direct_manager_name, m2.employee_name AS skip_level_manager_name FROM employees e LEFT JOIN employees m1 ON e.manager_id = m1.employee_id LEFT JOIN employees m2 ON m1.manager_id = m2.employee_id ORDER BY e.employee_id;

Why this works

For fixed-depth lookups, repeated self-joins are simpler and faster than recursive CTEs. They are also the only option on engines without recursive-CTE support (e.g., MySQL 5.7).

Success check

Every employee appears once with NULLs wherever the management chain ends.

Expected result

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

employee_idemployee_namedirect_manager_nameskip_level_manager_name
1Alice CEONULLNULL
2Bob VP SalesAlice CEONULL
3Carol VP EngAlice CEONULL
4David VP HRAlice CEONULL
5Emma Sales MgrBob VP SalesAlice CEO
6Frank Eng MgrCarol VP EngAlice CEO
7Grace HR MgrDavid VP HRAlice CEO
8Henry Sales RepEmma Sales MgrBob VP Sales
9Ivy Sales RepEmma Sales MgrBob VP Sales
10Jack EngineerFrank Eng MgrCarol VP Eng

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.