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')))
1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.