Recursive CTE Resolves Dependency Order

A recursive CTE levels every task one past its deepest dependency, so max(level) per task yields a safe execution order for the pipeline.

SqlCli Tooling

Code

snippet
-- 依赖图:task 需要先完成 depends_on 里的前置任务;RECURSIVE 让 levels 能引用自己
WITH RECURSIVE tasks(task) AS (
    VALUES ('migrate'), ('seed'), ('warm_cache'), ('serve')
),
task_deps(task, depends_on) AS (
    VALUES ('seed', 'migrate'),
           ('warm_cache', 'migrate'),
           ('warm_cache', 'seed'),
           ('serve', 'warm_cache')
),
-- resolves dependency order:层号 = 1 + 前置任务的最大层号,UNION 去重保证收敛
levels(task, level) AS (
    SELECT t.task, 0
    FROM tasks t
    WHERE NOT EXISTS (SELECT 1 FROM task_deps d WHERE d.task = t.task)
    UNION
    SELECT d.task, l.level + 1
    FROM task_deps d
    JOIN levels l ON d.depends_on = l.task
)
SELECT task, max(level) AS order_level
FROM levels
GROUP BY task
ORDER BY order_level, task;

How it works

What runs is SELECT, with tasks, task_deps and levels as the object involved.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause constraining which rows the statement operates on; MAX aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; a UNION merging rows produced by different queries.

Putting it to use

The tasks table is the working surface here.

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`tasks`, `task_deps`, `levels` — joined via one JOIN clause.