N052-H1 Tier 4 · Advanced · hard hr · Helix Systems

Return the ID, name, and step number for every person in the chain. Employee `id = 28` is at step `1`, their direct manager at step `2`, and so on up to the CEO

Part of Recursive CTEs in SQL

The problem

Helix Systems' security audit traces the full management chain for employee id = 28, from that employee upward through every level of management to the CEO.

Write a query to return the ID, name, and step number for every person in the chain. Employee id = 28 is at step 1, their direct manager at step 2, and so on up to the CEO.

Assumptions:

  • Employee id = 28 has a recorded manager_id. The CEO has a missing manager_id.
  • The chain starts with employee id = 28 at step 1 and moves upward — at each step, the next chain member is the employee whose id equals the current row's manager_id. The chain ends with the CEO, whose row is included.
  • The chain has exactly four members: employee id = 28 (step 1) and three managers above them up through the CEO.

Output:

  • One row per chain member, with columns id, name, and step.
Schema · hr 4 tables
departments
id integer
name text
location text
budget numeric
salaries
id integer
employee_id integer
amount numeric
effective_date date
end_date? date
employees
id integer
name text
email text
department_id integer
manager_id? integer
hire_date date
title text
is_active boolean
job_history
id integer
employee_id integer
title text
department_id integer
start_date date
end_date? date

Run previews · Check grades

Write a query, then run it to see results here.

Worked solution Try it yourself first
Solution query
WITH RECURSIVE
  chain AS (
    SELECT
      id,
      name,
      manager_id,
      1 AS step
    FROM
      employees
    WHERE
      id = 28
    UNION ALL
    SELECT
      e.id,
      e.name,
      e.manager_id,
      c.step + 1
    FROM
      employees e
      JOIN chain c ON e.id = c.manager_id
  )
SELECT
  id,
  name,
  step
FROM
  chain

The shape

The recursion walks upward from a single employee to the CEO. The anchor seeds the chain at employee id = 28, and the recursive member joins each subsequent row by matching the previous row's manager_id to the new row's id. This reverses the usual top-down direction: each pass adds the parent of the row already in the CTE rather than the child.

Clause by clause

  • The anchor seeds the chain at the target employee:
SELECT id, name, manager_id, 1 AS step
FROM employees
WHERE id = 28

Uri Vance enters chain at step = 1. The row carries his manager_id along with his own id because the recursion needs both to walk upward.

  • The recursive member adds each manager in the chain:
UNION ALL
SELECT e.id, e.name, e.manager_id, c.step + 1
FROM employees e
JOIN chain c ON e.id = c.manager_id

The join condition e.id = c.manager_id is the reversed link: the new row's id has to equal the source row's manager_id. Pass one finds Anna Kim, whose id matches Uri's manager_id. Pass two finds Marcus Reid, whose id matches Anna's. Pass three finds Sarah Chen, whose id matches Marcus's. Pass four finds no row whose id matches Sarah's manager_id, because Sarah's manager_id is NULL; the join can't match NULL to anything, and the recursion stops.

  • The final SELECT returns the chain:
SELECT id, name, step
FROM chain

Four rows, one per chain member, each carrying the step number that records how far up from Uri they sit.

Why this and not a downward walk filtered to the path

A downward walk would seed the anchor with the CEO and recurse all the way to every leaf, then filter the result to keep only the rows on Uri's path. That works, but it has to materialise every employee in the company just to discard all but four of them. Walking upward from the target visits exactly four rows — the anchor and the three managers — and never touches anyone else. When the question is "what is the chain above this one node," the upward walk is the shape that matches the question.

The trap

The CEO's row terminates the recursion specifically because their manager_id is NULL, and a join on e.id = c.manager_id can never match a NULL. That implicit termination is fine on a hierarchy where the root is the only NULL-managered employee. On data where multiple employees have a NULL manager_id — for example, contractors who report to no one — the upward walk from a non-CEO would still terminate at their first NULL-managered ancestor, which may or may not be the intended stopping point. A WHERE c.manager_id IS NOT NULL inside the recursive member's filter makes the termination rule explicit instead of implicit; both spellings work here, but the explicit form is more robust if the data could carry multiple roots.

You practiced upward WITH RECURSIVE traversal — instead of linking child→parent, the recursion links parent→child by matching the outer record's id to the inner record's manager_id, walking the chain in reverse.

How you actually get good at SQL

Reading explains SQL. Writing it, over and over with instant feedback, is what makes you fluent.

That's the whole SQLMaxx loop: 600+ real problems, instant AI feedback, mastery you can actually see, and spaced review that won't let you forget.

A stack of SQL practice problem cards, the top card showing an employees table.
615 problems · 66 concepts

Real problems. Not toy examples.

615 hand-built problems spanning all 66 concepts, from basic SELECTs to window functions, built on real schemas and real business questions, the kind you'll actually get asked on the job. Enough reps to make SQL automatic.

A retro computer showing a SQL query marked correct with a green checkmark.
Instant AI feedback

Write a query. Know if it's right in one second.

No copying an answer and hoping it clicked. The AI grader checks your real query against real data, catches exactly what's wrong, and explains the fix in plain English, like a senior analyst reading over your shoulder on every problem.

A circular mastery progress dial filling from blue to green, the SQLMaxx diamond at its center.
Mastery tracking

Stop guessing whether you actually know it.

SQLMaxx tracks every concept and shows you what you've mastered and what's still shaky. Your skills fill in one concept at a time, so 'I think I get joins' becomes something you can prove.

A SQL query editor circled by a blue return arrow with a clock, scheduled to come back for review.
Spaced review

Learn it once. Keep it for good.

Most of what you learn this week fades by next week. So when a concept comes due for review, SQLMaxx hands you a fresh problem to solve from a blank editor, not a flashcard to re-read. A research-backed spaced-repetition algorithm (FSRS) times each return for right before you'd forget, so your SQL is still there months later, when the interview or the job actually needs it.

Practice, feedback, mastery, review. That's the loop that turns reading into real skill.

Start free

No account, no credit card. Start solving in under a minute.