Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Standard relational tables store flat sets of rows, yet real-world enterprise data is filled with hierarchies, trees, and graphs:
Before MySQL 8.0, querying arbitrarily deep hierarchies required recursive application code or complex stored procedures. Recursive Common Table Expressions (WITH RECURSIVE) solve this problem natively within pure SQL.
A recursive CTE consists of three indispensable components:
UNION ALL (or UNION): Joins the anchor results to the subsequent recursive iterations.To generate a sequence of numbers from 1 to 5:
Output: 1, 2, 3, 4, 5.
Suppose an employees table has an employee_id and a manager_id pointing to their supervisor:
Querying the entire reporting line from the CEO down to junior developers with depth levels:
If cyclical references occur (e.g., Employee A manages Employee B, and Employee B manages Employee A), recursion could loop indefinitely, exhausting memory.
MySQL protects against runaway execution using the cte_max_recursion_depth system variable:
If a query exceeds this limit, MySQL immediately aborts with: ERROR 3636 (HY000): Recursive query aborted after 51 iterations.
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Chaining Multiple CTEs in a Single Query | CTEs vs Subqueries vs Views Comparison |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.