add batch remove batch split batch comment selection show hidden batches hide batch highlight batch
db<>fiddle
donate feedback about
By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
create table organization(
id int,
name varchar(10),
parent_id int
);

insert into organization values
( 1, 'Org1', 2),
( 2, 'Org2', NULL),
( 3, 'Org3', 5),
( 5, 'Org5', 1),
(14, 'Org14', 1);


WITH RECURSIVE cte (id, name, parent_id, dir) AS (
SELECT id, name, parent_id, cast(null as char(10)) as dir
FROM organization
WHERE id = 1
UNION
SELECT t1.id, t1.name, t1.parent_id, ifnull(t2.dir, 'down')
FROM organization t1
INNER JOIN cte t2 ON t1.parent_id = t2.id and ifnull(t2.dir, 'down')='down'
UNION
SELECT t1.id, t1.name, t1.parent_id, ifnull(t2.dir, 'up')
FROM organization t1
INNER JOIN cte t2 ON t2.parent_id = t1.id and ifnull(t2.dir, 'up')='up'
)
SELECT id, name, parent_id FROM cte;


Records: 5  Duplicates: 0  Warnings: 0
id name parent_id
1 Org1 2
5 Org5 1
14 Org14 1
2 Org2 null
3 Org3 5