How to relate two rows with cyclic relationship in the same table in sql?
I'm not sure to understand correctly your use case, but maybe you could simply do the update comparing refer_to_id and id columns.

update my_table
set group_id =  case when refer_to_id &gt; id then id 
                    when  refer_to_id &lt; id then refer_to_id 
                    else id 
                end


This is really basic and will not fix your issue if you have complex dependencies (line #1 referring to line #2 referring to line #3 etc...).