Exercise 3: Why depth DESC Produces Root-to-Leaf Order — Possible Solution ==================================================================== WHY ORDER BY depth DESC WORKS ------------------------------ Per this chapter, the base case assigns depth = 0 to the target page itself. Each recursive step, climbing one level further up toward the root, increments depth by 1. This means the target page always has the smallest depth value (0), and the furthest-back root ancestor always has the largest depth value in the result set. Sorting by depth DESC therefore puts the largest depth - the root - first, and depth 0 - the target page itself - last, which is exactly root-to-leaf order. WITHOUT THE depth COLUMN AND ORDER BY CLAUSE ------------------------------ WITH RECURSIVE ancestors AS ( SELECT * FROM pages WHERE id = ? UNION ALL SELECT p.* FROM pages p INNER JOIN ancestors a ON p.id = a.parent_id ) SELECT * FROM ancestors; Removing depth and ORDER BY leaves the row order entirely up to MySQL's own internal execution order for the recursive CTE, which is not guaranteed to be root-to-leaf, leaf-to-root, or any other specific order - the result set is correct in CONTENT (the right rows) but not reliably correct in ORDER for rendering a breadcrumb directly. WHY THIS WORKS AS AN ANSWER ------------------------------ It correctly explains why depth increases while climbing toward the root, correctly explains why DESC ordering therefore produces root-to-leaf order, and correctly confirms that removing the ordering mechanism leaves row order unreliable even though the same correct set of rows is still returned.