I have a table that contain employee, manager, ceo, etc
viewer_org_id  | path     |  name    |  id
    1             1          Razor       1
    1             1.2        Michael     2
    2             1.2        Michael     2
    1             1.2.3      Romus       3
    2             1.2.3      Romus       3
    3             1.2.3      Romus       3
    1             1.2.3.4    Lion        4
    2             1.2.3.4    Lion        4
    3             1.2.3.4    Lion        4
    4             1.2.3.4    Lion        4
Razor is a Ceo, Michael is a manager, Romus is employee and Lion is Romus' assistant.
the viewer_org_id field is generated by using string_to_aray() of path field, so you can see they are sequence of path-link. The id is id of employee-name.
The output table is
bases  | part_id  |  part_of  |  viewer_org_id   |  name   | id
Razor       1         Razor          1              Razor    1
Razor       1         Razor          1              Michael  2
Michael     2         Michael        2              Michael  2
Razor       1         Razor          1              Romus    3
Razor       1         Michael        2              Romus    3
Michael     2         Michael        2              Romus    3
Romus       3         Romus          3              Romus    3
Razor       1         Razor          1              Lion     4
Razor       1         Michael        2              Lion     4
Michael     2         Michael        2              Lion     4
Razor       1         Romus          3              Lion     4
Michael     2         Romus          3              Lion     4
Romus       3         Romus          3              Lion     4
Lion        4         Lion           4              Lion     4
let's say i have a table employee. i have tried to query by CTE, shown below;
with em
as (select 
           a.name
           b.viewer_org_id,
           b.name as data_org_name,
           b.org_id data_org_id
    from (select distinct name org_id from employee) a
    join (select viewer_org_id, name, org_id from employee) b
         on b.viewer_org_id = a.org_id)
select 
      nn1.name bases,
      nn1.viewer_org_id part_id,
      nn2.name part_of,
      nn2.viewer_org_id,
      nn2.data_org_name name,
      nn2.data_org_id org_id
from em nn1
join em nn2
     on nn1.data_org_id = nn2.viewer_org_id
this query has worked but not optimal, the cost still big enough. Can anyone tell me how to make recursive CTE with 3 level or how to be more effective query? i have tried but there's no way. thank you in advance
 
    