Lompati ke konten utama
eLearner.app
Modul 14 · Pelajaran 3 dari 355/57 dalam kursus~18 min
Pelajaran modul (3/3)

CTE Rekursif: data berbentuk pohon

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;
Latihan#sql.m14.l3.e1
Upaya: 0Memuat…

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.

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya

Latihan#sql.m14.l3.e2
Upaya: 0Memuat…

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.

Memuat editor…
Tunjukkan petunjuk

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

Solusi tersedia setelah 3 upaya