hgunawan
9/15/2019 - 2:44 AM

postgre cte recursive

postgre cte recursive

# https://www.db-fiddle.com/f/qWfEmKbnbdAVHH8W1G4kpy/0
create table table1
(
id int,
parent int
);

insert into table1 
values
	(1,NULL),
    (2,1),
    (3,1),
    (4,2),
    (5,2),
    (6,2),
    (7,3),
    (8,4);

WITH RECURSIVE ctetable as 
(
    SELECT S.id, S.parent, 
  		1 AS depth, 
  		cast(S.id as varchar(100)) AS path
    FROM table1 as S
    UNION ALL
    SELECT S2.id, p.parent, 
        p.depth + 1 AS depth, 
        cast(
          CONCAT(RTRIM(p.path), '->', cast(S2.id as varchar(100)))
        as varchar(100))
    FROM ctetable AS p 
    JOIN table1 as S2 on S2.parent = p.id
    WHERE p.parent is not null                                                            
)
SELECT * FROM ctetable 
ORDER BY id, parent;