Adjusting Child Order in Hierarchical SQL Structures

Using SQL (MS-SQL 2005), how can I update the OrderPosition for child nodes after a sibling deletion?

-- Define the ProjectItems table
CREATE TABLE ProjectItems (
    ItemID INT PRIMARY KEY,
    ParentItemID INT,
    OrderPosition INT,
    Description NVARCHAR(100)
);

I implemented a solution where I directly updated the OrderPosition using a correlated subquery instead of relying on a separate temporary table or CTE structure. This approach recalculates the position on the fly by comparing the deleted node’s value and shifting the positions of subsequent siblings. It was encapsulated in a single transaction to ensure consistency during concurrent operations and minimize the chance of data conflicts. This method proved effective in practice, especially where the data involved was of moderate size and performance considerations were crucial.

The approach I found most effective involves recalculating the OrderPosition values for the remaining sibling nodes after deletion. In practice, I start by selecting the child nodes for the parent in question, ordering them based on their previous OrderPosition, and then assigning new sequential numbers. A common pattern is to use a temporary table or a common table expression to hold the updated values and then perform an update on the original table. This method ensures that the sequence is restored correctly and minimizes impact on database performance.

hey, i like the idea of using a cte to reassign order pos after deletions. have you experimented with window funtions like row_number? sometimes a direct update feels tricky. what are your thots on performance issues in this scenario?

i tried a version using row_number in a subquery and wrapped it in a trnsaction for safety. it fixes the orderpos quickly after deletions even if not perfect in performance!