Mid-level Track Roadmap

Advanced SQL: CTE mastery

This course covers recursive CTEs in PostgreSQL, built against the community_comments table, the app's one self-referential model. It explains why a two-query thread loader stops working when reply depth is unknown. It uses Rails' with_recursive method, with an anchor and a recursive member joined by UNION ALL. It adds depth and path columns, guards against cycles that a foreign key does not prevent, and explains why recursive CTEs are always materialized. It closes with data-modifying CTEs and why this app's services do not use them.

What you'll learn

  • ✓Writing recursive CTEs with Rails' with_recursive method
  • ✓How the anchor and the recursive member run round by round
  • ✓Computing depth and path inside the recursive member
  • ✓Stopping cycles with a path-based guard
  • ✓Why recursive CTEs are always materialized and how their cost grows
  • ✓Data-modifying CTEs with RETURNING and why this app avoids them
Free preview · Lesson 1 4 min read

The one thing WITH couldn't do

The junior course "ActiveRecord: CTE basics" closed its first lesson with a promise. It named what it left out: a CTE that references itself, WITH RECURSIVE, for tree- and graph-shaped data such as an org chart or "a comment thread's replies". It called itself "deliberately the non-recursive half".…

Read the full lesson free →

Curriculum

7 lessons
Type to start searching...