Tracking depth
- SQL course
- Advanced
- Lesson 10/81
- 4 min
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
-- sort by level
SELECT name, level FROM orgSample solution
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
SELECT name, level FROM org ____ level;
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 |