1

Am a beginner in SQL. How can I optimize this query

select * from t1 where parent_id in (select id from t1 where id= 'X')

UNION

select * from t1 where parent_id in (select id from  t1 where parent_id in (select id from t1 where id= 'X'))
UNION

select * from t1 where parent_id in (select id from t1 where parent_id in (select id from  t1 where parent_id in (select id from t1 where id= 'X')))
Kinara Nyakaru
  • 489
  • 6
  • 14
  • 1
    Possible duplicate of [Find Parent Recursively using Query](https://stackoverflow.com/questions/3699395/find-parent-recursively-using-query) – Nir Alfasi May 02 '19 at 21:25

1 Answers1

1

You can try with recursive cte:

WITH RECURSIVE cte AS (
  select * from t1 where t1.id='X'
  union all
  select t1.*
  from cte c
    join t1
      on t1.id=c.parent_id
)
select distinct * from cte
James
  • 2,954
  • 2
  • 12
  • 25