Recursion will be the easiest way to handle this:-- *** Consumable Test Data ***-- Please provide in futureCREATE TABLE #t( ID int NOT NULL ,Source_ID int NULL);INSERT INTO #tVALUES(147, NULL),(575, NULL),(2221, NULL),(2791, NULL),(5478, NULL) ,(7115, NULL),(7242, NULL),(7493, NULL),(7499, NULL),(7500, NULL) ,(7517, NULL),(7590, NULL),(7595, NULL),(7596, NULL),(7608, NULL) ,(7609, 7595),(7610, 7517),(7611, 2791),(7612, 575),(7613, 7242) ,(7614, 7499),(7615, 7115),(7616, NULL),(7617, 7616),(7619, 7500) ,(7620, 147),(7622, 7493),(7623, 7620),(7625, 7590),(7626, 7596) ,(7627, 5478),(7628, 7627),(7630, 7608);-- *** End Test Data ***WITH HierarchyAS( SELECT ID, Source_ID ,ID AS TopID FROM #t WHERE Source_ID IS NULL UNION ALL SELECT T.ID, T.Source_ID ,H.TopID FROM #t T JOIN Hierarchy H ON T.Source_ID = H.ID)SELECT ID, Source_IDFROM HierarchyORDER BY TopID, ID;