Using a sort order column in a database table

Update product set order = order+1 where order >= @value changed

Though over time you’ll get larger and larger “spaces” in your order but it will still “sort”

This will add 1 to the value being changed and every value after it in one statement, but the above statement is still true. larger and larger “spaces” will form in your order possibly getting to the point of exceeding an INT value.

Alternate solution given desire for no spaces:

Imagine a procedure for: UpdateSortOrder with parameters of @NewOrderVal, @IDToChange,@OriginalOrderVal

Two step process depending if new/old order is moving up or down the sort.

If @NewOrderVal < @OriginalOrderVal --Moving down chain 

--Create space for the movement; no point in changing the original 
    Update product set order = order+1 
    where order BETWEEN @NewOrderVal and @OriginalOrderVal-1;

end if

If @NewOrderVal > @OriginalOrderVal --Moving up chain

--Create space  for the momvement; no point in changing the original  
  Update product set order = order-1 
  where order between @OriginalOrderVal+1 and @NewOrderVal
end if

--Finally update the one we moved to correct value

    update product set order = @newOrderVal where ID=@IDToChange;

Regarding best practice; most environments I’ve been in typically want something grouped by category and sorted alphabetically or based on “popularity on sale” thus negating the need to provide a user defined sort.

Leave a Comment