Here is "a" solution. It is probably very fragile solution (I don't have time to come up with a robust solution),but it works with your sample data:DECLARE @Foo TABLE (ITEM1 INT, ITEM2 INT, ID INT)INSERT @Foo (ITEM1, ITEM2) VALUES(0224180, 0224181),(0224180, 0224190),(0224181, 0224180),(0224181, 0224190),(0224190, 0224180),(0224190, 0224181),(0202294, 0202295),(0202295, 0202294),(0209250, 0209251),(0209251, 0209250)DECLARE @Val1 INT;DECLARE @Val2 INT;DECLARE @Iterator INT = 1;-- Prime LoopSELECT TOP 1 @Val1 = Item1, @Val2 = Item2 FROM @FooORDER BY Item1WHILE @Val1 IS NOT NULLBEGIN -- Perform Update UPDATE @Foo SET ID = @Iterator WHERE Item1 IN (@Val1, @Val2) OR Item2 IN (@Val1, @Val2); -- Get next item/group SELECT TOP 1 @Val1 = Item1, @Val2 = Item2 FROM @Foo WHERE Item1 NOT IN (@Val1, @Val2) AND Item2 NOT IN (@Val1, @Val2) AND ID IS NULL ORDER BY Item1 IF @@ROWCOUNT = 0 BEGIN SET @Val1 = NULL; END SET @Iterator = @Iterator + 1;ENDSELECT *FROM @Foo