CodeBlanks Logo Icon CodeBlanks

Hierarchy report

Write an org-chart report with a recursive CTE.

Hierarchy report

In this challenge you will extract an org hierarchy with a recursive CTE.

WITH RECURSIVE org AS (
  SELECT id, name, manager_id, 1 AS level
  FROM employees WHERE manager_id IS NULL
  UNION ALL
  SELECT e.id, e.name, e.manager_id, o.level + 1
  FROM employees e JOIN org o ON e.manager_id = o.id
)
SELECT * FROM org ORDER BY level;

Organization tree.

WITH RECURSIVE defines a self-referencing temporary result set (CTE) named org; the query after it uses it like a table. All columns are selected from org. The result is sorted by level in ascending order.

Practice Hierarchy report

Extract the org hierarchy with a recursive CTE: anchor the root, recursively add subordinates.

Starter code

query.sql
-- write the recursive CTE for the hierarchy report
-- use the employees table

Sample solution

query.sql
WITH RECURSIVE org AS (
  SELECT id, name, manager_id, 1 AS level
  FROM employees WHERE manager_id IS NULL
  UNION ALL
  SELECT e.id, e.name, e.manager_id, o.level + 1
  FROM employees e JOIN org o ON e.manager_id = o.id
)
SELECT * FROM org ORDER BY level;

Expected output

id  name    level
1   Fatma   1
2   Ayşe    2

Questions and answers

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

1 What joins in a recursive CTE?

  • UNION ALL Correct answer
  • INTERSECT
  • JOIN
  • EXCEPT

Explanation: A recursive CTE joins with UNION ALL.

2 Hierarchy report: match the terms

Term Meaning
recursive recursive
anchor base
UNION ALL combine
level depth

All lessons in Advanced