Ana içeriğe geç
eLearner.app
Modül 14 · Ders 3 ders 3Kurstaki 55/57~18 min
Modül dersleri (3/3)

Özyinelemeli CTE'ler: ağaç şeklindeki veriler

Recursive CTEs: Tree-shaped Data

Now we get to the real superpower of CTEs. There are situations where data has endlessly nested parent relationships (the classic e-commerce categories arranged as MacBook > Computer > Electronics > Products). Plain SQL struggles to walk these hierarchies without loops.

A Recursive CTE solves this by calling itself, pulling out parent/child levels until it "exhausts" the dependency stack.

How it's built

You need the WITH RECURSIVE keyword, and it splits into 2 required parts separated by UNION ALL:

  1. Base case (the query that extracts the root parents or the starting element).
  2. Recursive step (the query that joins onto itself to pull in the children).
SQL
WITH RECURSIVE branch AS (
  -- Base case: find the top-level category that has no parent (parent_id IS NULL)
  SELECT id, name, parent_id, 1 AS depth
  FROM categories
  WHERE parent_id IS NULL

  UNION ALL

  -- Recursion: pulls in the children that point to parents found in the previous step
  SELECT c.id, c.name, c.parent_id, b.depth + 1
  FROM categories c
  JOIN branch b ON c.parent_id = b.id
)
SELECT * FROM branch ORDER BY depth;
Egzersiz#sql.m14.l3.e1
Denemeler: 0Yükleniyor…

Trace the basic hierarchy. Create a recursive CTE 'cat_tree'. Base case: Select 'id', 'name' from the 'categories' table where 'parent_id IS NULL'. Then recursively UNION the subcategories ('categories c') JOINed to 'cat_tree t' on 'c.parent_id = t.id'. Finally SELECT * FROM cat_tree.

Düzenleyici yükleniyor…
İpucu göster

Use WITH RECURSIVE cat_tree AS (base_case UNION ALL recursive_case).

3 denemeden sonra çözüm mevcut

Egzersiz#sql.m14.l3.e2
Denemeler: 0Yükleniyor…

Modify cat_tree to compute the concept of 'level'. Base case: add a hardcoded '1 AS depth', and include the \`parent_id\` (id, name, parent_id, depth). Recursive case: the child categories will increment the depth with 't.depth + 1'. Show everything ordered by depth ASC.

Düzenleyici yükleniyor…
İpucu göster

Add 't.depth + 1'. Run the final SELECT with ORDER BY depth.

3 denemeden sonra çözüm mevcut