CodeBlanks Logo Icon CodeBlanks

Tracking depth

Compute each row's depth level.

Depth level

In a recursive CTE the level column shows the hierarchy depth. It increments each step.

SELECT name, level FROM org ORDER BY level;

This query shows each person's level.

name, level is selected from org. The result is sorted by level in ascending order.

Depth level — details

level starts at 1 in the anchor, +1 in the recursive step. Depth makes the hierarchy easier to understand.

If you sort the result with ORDER BY level you see the top manager first and then the people below, level by level; WHERE level <= 2 returns only the first two levels.

Practice Depth level

Sort the recursive CTE results by the level column.

Starter code

query.sql
-- sort by level
SELECT name, level FROM org

Sample solution

query.sql
SELECT name, level FROM org ORDER BY level;

Expected output

name    level
Fatma   1
Ayşe    2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens to level each step?

  • Stays the same
  • Increases by 1 Correct answer
  • Decreases
  • Resets to zero

Explanation: Level increments by +1 each step.

2 Add ORDER BY

Question
SELECT name, level FROM org ____ level;
Answer
SELECT name, level FROM org ORDER BY level;

Explanation: ORDER BY is the right answer.

3 Tracking depth: match the terms

Term Meaning
level depth
+1 increments
anchor 1
step loop

All lessons in Advanced