0
--------------+-------------------+
           id |         parent_id |
--------------+-------------------|
           18 |            <null> |
           20 |            <null> |
           25 |                18 |
--------------+-------------------+

I want my query to select all ids where its id doesn't exist in parent_id column. How would I go about doing that?

1 Answer 1

1

Easiest way is to do use NOT EXISTS to return those id's not found in the parent_id column:

select id
from tablename t1
where not exists (select 1 from tablename t2
                  where t2.parent_id = t1.id)

NOT IN may also be used, but be careful, NULL's have to be taken care of:

select id
from tablename
where id not in (select parent_id from tablename
                 where parent_id is not null)
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.