To keep it simple I left out LIMIT
(so we also don't need extra parentheses) and WHERE
of your original query. Those can be added freely.
Basic query
WITH RECURSIVE node_rec AS (
(
SELECT 1 AS depth, *
, ARRAY[node] AS path
FROM nodes
WHERE parent IS NULL
LIMIT 10
)
UNION ALL
SELECT r.depth + 1, n.*
, r.path || n.node
FROM node_rec r
JOIN nodes n ON n.parent = r.node
WHERE r.depth < 4
)
SELECT *
FROM node_rec
ORDER BY path;
WITH RECURSIVE node_rec AS (
(
SELECT 1 AS SELECTdepth, *
FROM nodes
WHERE parent IS NULL
LIMIT 10
)
UNION ALL
SELECT r.depth + 1, n.*
FROM node_rec r
JOIN nodes n ON n.parent = r.node
) SEARCH DEPTH FIRST BY node SET path
SELECT *
FROM node_rec
ORDER BY path, ts;
AdditionalOrder by additional column as tiebreaker
-- sort by path, peers on the same level by timestamp
WITH RECURSIVE node_rec AS (
(
SELECT 1 AS depth, *
, ARRAY[(ts, node)] AS path
FROM nodes
WHERE parent IS NULL
LIMIT 10
)
UNION ALL
SELECT r.depth + 1, n.*
, r.path || (n.ts, n.node)
FROM node_rec r
JOIN nodes n ON n.parent = r.node
WHERE r.depth < 4
)
SELECT *
FROM node_rec
ORDER BY path;
WITH RECURSIVE node_rec AS (
(
SELECT 1 AS depth, *
FROM nodes
WHERE parent IS NULL
LIMIT 10
)
UNION ALL
SELECT r.depth + 1, n.*
FROM node_rec r
JOIN nodes n ON n.parent = r.node
) SEARCH DEPTH FIRST BY ts, node SET path
SELECT *
FROM node_rec
ORDER BY path, ts;