I'm using a Postgres CTE to recurse through a parent-child tree. The following script will recurse from root to leaf and append to the end of path (ARRAY).
WITH RECURSIVE tree AS (
// get roots
SELECT entity_id, parent_id, ARRAY[entity_id] as path
FROM entity
WHERE parent_id is null
UNION ALL
// recursive step
SELECT c.entity_id, c.parent_id, path || c.entity_id
FROM tree t
JOIN entity c ON c.parent_id = t.entity_id
)
SELECT path
FROM tree t
WHERE entity_id NOT IN (SELECT DISTINCT parent_id FROM tree WHERE parent_id IS NOT NULL);
Instead of appending to the end of the path at each step, I would like to insert into the array by a index column. Is it possible to do this within SELECT?
Hypothetical Solution
SELECT path[c.index] = c.entity_id
FROM tree t
JOIN entity c ON c.parent_id = t.entity_id
Expected output
| entity_id | index | parent_id |
|:-----------|------------:|:----------|
| a | 3 | d |
| b | 5 | a |
| c | 1 | (none) |
| d | 2 | c |
path = [c,d,a,(none),b]
indexcomes from? The expression ` path[c.index] = path[entity_id]` is certainly valid ifc.indexandentity_idare both integer valuespath[c.index] = c.entity_id. That expression returns a boolean which throws error on union