← Back to PostgreSQL Course | Chapter 8: Subqueries & CTEs | Lesson 6 of 7

Recursive CTEs का उपयोग

एक recursive CTE अपने output पर एक query repeat करता है, जो trees walk करने और sequences generate करने का तरीका है।

In this page:

  1. Recursive CTEs
Syntax
sql
WITH RECURSIVE cte_name AS (
  SELECT columns FROM table_name WHERE anchor_condition
  UNION ALL
  SELECT columns FROM table_name t JOIN cte_name c ON t.parent_id = c.id
)
SELECT * FROM cte_name;

Recursive CTEs

WITH RECURSIVE में एक anchor query (starting rows), UNION ALL, और एक recursive query है जो CTE को खुद reference करती है।

यह तब रुकता है जब recursive part कोई नई rows return न करे। इसे organisation charts या category trees जैसी hierarchies के लिए इस्तेमाल करें।

एक depth limit से infinite loops के against guard करें।

Note: cycles से बचाव के लिए एक depth column या LIMIT add करें।

उदाहरण: Recursive CTEs

sql
CREATE TABLE staff (id INTEGER PRIMARY KEY, name TEXT, manager_id INTEGER);
INSERT INTO staff VALUES (1,'Ada',NULL),(2,'Bob',1),(3,'Cy',1),(4,'Di',2),(5,'Ed',4);
WITH RECURSIVE chain(id, name, depth) AS (
  SELECT id, name, 0 FROM staff WHERE manager_id IS NULL
  UNION ALL
  SELECT s.id, s.name, c.depth + 1 FROM staff s JOIN chain c ON s.manager_id = c.id
)
SELECT name, depth FROM chain ORDER BY depth, name;
WITH RECURSIVE counter(n) AS (SELECT 1 UNION ALL SELECT n + 1 FROM counter WHERE n < 5)
SELECT n FROM counter;

-- Output:
-- name | depth
-- Ada | 0
-- Bob | 1
-- Cy | 1
-- Di | 2
-- Ed | 3
-- n
-- 1
-- 2
-- 3
-- 4
-- 5
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. termination condition भूल जाना
  2. data में cycles से infinite loops बनना
  3. बेवजह UNION ALL की बजाय UNION इस्तेमाल करना
चैप्टर सारांश
  • Anchor और recursive term दोनों चाहिए
  • UNION ALL इन्हें combine करता है
  • जब कोई नई rows न आएँ रुकता है
  • Hierarchies के लिए ideal
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.