I have a table including the columns (int id pkey, int group, double sortOrder) where sortOrder implements a user-specified sort order within one group. On some modifications, I need to re-number the sort order of all items in the group. SortOrder values in different groups are independen of each other (i.e. they are only ever compared within one group)
SELECT id, sortOrder FROM tbl WHERE group=X ORDER BY SortOrder
Gives me all elements in that group, in the current order, in whch I would have to assign sequential values (1, 2, 3, …) to SortOrder.
Q: Is there any reasonable way – preferrably portable to other SQL implementations – to do that without updating every row individually?
More info: I am using doubles, because that allows to trivially assign a new sort order without modifying other items (MIN-1 for before, MIN+1 for insert at end, and (A+B)/2 for inserting between A and B.) – this is limited of course by double resolution (~52 inserts in the worst case). I’m not sure yet if this is worth the additional checking for overflow, but I’d have the same problem with any other data type anyway.
The only other idea I came up with was simulating infinite resolution with strings and custom COLLATE and ADD/SUB/AVG functions. However, this seems immensely non-portable.
I don’t believe that SQLite has a trivial way of doing this.
What you may be better looking at (if this really is a concern) is sticking with integer sorting and implementing an algorithm that maintains the sequence.
If, for example, all changes to sorting involve moving an item up/down one place, you just need to swap the sort orders of both values…
Or if you can move an item to any position, use something like…
I’m aware that you said that you don’t want to update other items each time, but this has actually proven to be pretty efficient in most cases for me in the past.