WITH NewListOrder AS (select patientprofileid,patientrelationshipid,ROW_NUMBER() OVER (PARTITION BY patientprofileid order by patientrelationshipid) as listorder from patientrelationship) update patientrelationship set listorder=nl.listorder from patientrelationship pr join newlistorder nl on pr.patientprofileid=nl.patientprofileid and pr.patientrelationshipid=nl.patientrelationshipid