N052-M1 Tier 4 · Advanced · medium hr · Helix Systems

Return the ID, name, and depth level for every employee

Part of Recursive CTEs in SQL

The problem

Helix Systems' HR platform needs a complete view of the organizational hierarchy.

Write a query to return the ID, name, and depth level for every employee.

Assumptions:

  • The CEO has a missing manager_id. Every other employee has a manager_id referencing another employee's id.
  • The CEO is at depth 1, employees who report directly to the CEO are at depth 2, employees who report to a depth-2 employee are at depth 3, and so on through every reporting level.
  • Every employee appears in the result exactly once.

Output:

  • One row per employee, with columns id, name, and depth.
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
  org AS (
    SELECT
      id,
      name,
      manager_id,
      1 AS depth
    FROM
      employees
    WHERE
      manager_id IS NULL
    UNION ALL
    SELECT
      e.id,
      e.name,
      e.manager_id,
      o.depth + 1
    FROM
      employees e
      JOIN org o ON e.manager_id = o.id
  )
SELECT
  id,
  name,
  depth
FROM
  org

The shape

The recursion has no depth filter, so it keeps adding levels until no employee remains whose manager_id matches a row already in the CTE. On a tree-shaped reporting structure that has no cycles, the recursion terminates naturally once every leaf has been added.

Clause by clause

  • The anchor seeds the CEO at depth 1:
SELECT id, name, manager_id, 1 AS depth
FROM employees
WHERE manager_id IS NULL

Sarah Chen is the only row with a missing manager_id. She enters org carrying depth = 1.

  • The recursive member adds every employee whose manager is already in org:
UNION ALL
SELECT e.id, e.name, e.manager_id, o.depth + 1
FROM employees e
JOIN org o ON e.manager_id = o.id

Pass one matches every employee whose manager_id = 1 and stamps them with depth = 2 — Marcus, Priya, James, Lisa, and the rest of the direct reports. Pass two matches every employee whose manager_id is one of those depth-2 ids and stamps them with depth = 3. Pass three reaches depth 4. Pass four finds no rows whose manager_id matches any of the depth-4 ids, and the recursion stops.

  • The final SELECT reads the accumulated hierarchy:
SELECT id, name, depth
FROM org

All sixty employees are in org by now: one at depth 1, nine at depth 2, nineteen at depth 3, and thirty-one at depth 4.

Why no depth limit

A depth limit is the defense against cycles or against runaway traversal on unbounded graphs. A reporting hierarchy with a single root and no employee reporting to themselves directly or indirectly is a tree — every employee is reachable in exactly one path from the CEO, and the recursion converges on its own. Adding WHERE o.depth < N here would either be a no-op (if N is at or above the tree's true depth) or would silently truncate the result (if N is too low). For a clean tree, natural termination is the right behavior.

The trap

Natural termination assumes the reporting graph is acyclic. If a single employee's manager_id were edited to point at one of their own subordinates, the recursive join would match forever and the query would run until PostgreSQL killed it on a resource limit. The price of dropping the depth filter is the assumption that the data is clean. In production code against editable HR data, a defensive depth cap (WHERE o.depth < 20 or similar) is the standard belt-and-braces guard even when the data is expected to be a tree.

You practiced unbounded WITH RECURSIVE traversal — recurse until no new rows can be added; when the data is a clean tree, the recursion terminates naturally at the leaves.

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.