SQL Server - Select parent row or child row if no parent
Join the same table twice and use a CASE statement:

select
    case when t2.id is not null then t2.id else t1.id end as id,
    case when t2.id is not null then t2.childid else t1.childid end as childid
from 
    tbl t1
left join tbl t2
    on t2.childid = t1.id




id | childid
-: | ------:
 4 |       1
 2 |       3
 2 |       3
 4 |       1
 5 |    null
 6 |    null



db&lt;>fiddle here