Recursive CTE Shortest Path By Cost

Accumulate edge cost and visited path in a recursive CTE; a strpos guard stops cycles and the outer query keeps each node's cheapest route.

SqlData Fetching

Code

snippet
CREATE TABLE roads (
    src    text NOT NULL,
    dst    text NOT NULL,
    weight int  NOT NULL
);

INSERT INTO roads VALUES
    ('A', 'B', 2), ('A', 'C', 5),
    ('B', 'C', 1), ('B', 'D', 4),
    ('C', 'D', 1);

-- 递归展开所有简单路径:cost 累加边权,path 记录轨迹
WITH RECURSIVE routes AS (
    SELECT 'A'::text AS node, 0::int AS cost, 'A'::text AS path
    UNION ALL
    SELECT r.dst, v.cost + r.weight, v.path || '-' || r.dst
    FROM routes v
    JOIN roads r ON r.src = v.node
    -- 路径里已出现的节点不再踏足:strpos 守卫同时挡住环
    WHERE strpos(v.path, r.dst) = 0
),
best AS (
    SELECT node,
           MIN(cost) AS best_cost,
           (ARRAY_AGG(path ORDER BY cost))[1] AS best_path
    FROM routes
    GROUP BY node
)
SELECT * FROM best ORDER BY node;

-- 答案可手推:A-B-C-D = 2+1+1 = 4,比 A-B-D(6) 与 A-C-D(6) 都便宜

How it works

SELECT / INSERT / CREATE statements share the script, touching roads, routes and best.

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 limiting a statement to the rows that qualify; MIN aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; a UNION stitching together the result sets of separate queries; NOT NULL qualifiers on the required columns.

Putting it to use

The roads table is the working surface here.

Core lines

INSERT INTO roads VALUES
    ('A', 'B', 2), ('A', 'C', 5),
    ('B', 'C', 1), ('B', 'D', 4),
    ('C', 'D', 1);
CREATE TABLE roads (
    src    text NOT NULL,
    dst    text NOT NULL,
    weight int  NOT NULL
);

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`roads`, `routes`, `best`, combined through a join.