Scenario:
There is a database of movies a user owns, movies are displayed on a page called \"my-movies\", the movies can be displayed in the order that the user desires.
Store the order linked-list style. Instead of saving the absolute position, save the ID of the previous item. That way any change only requires you to update two rows.
movieid | userid | previousid
1 | 1 |
2 | 1 | 1
3 | 1 | 4
4 | 1 | 2
To get the movies in order ...
SELECT movieid WHERE userid = 1 ORDER BY previousid
-> 1, 2, 4, 3
To (say) move #4 up a space:
DECLARE @previousid int, @currentid int
SET @previousid = SELECT previousid FROM movies WHERE movieid = @currentid
-- current movie's previous becomes its preceding's preceding
UPDATE movies SET previousid =
(SELECT previousid FROM movies WHERE movieid = @previousid)
WHERE movieid = @currentid
-- the preceding movie's previous becomes the current one's previous
UPDATE movies SET previousid = @currentid WHERE movieid = @previousid
That's still 1 read + 2 writes, but it beats 10,000 writes.