I need to make a design decision about database. The requirment is that one database table has an *AUTO_INCREMENT PRIMARY KEY* field called id. By default, each row is shown to user (in web) sorted ascendenting by id. For example, if there are 4 records in the table. The UI will show rows in sequence of 0, 1, 2, 3.
Now, there is requirement that user can drag & drop row in UI to change sequence. Say, user drag rom 3 and drop it befow 0. So, the display sequence turns to be 3, 0, 1, 2. This sequence should be persistent into database.
I'm wondering how to design database table to make this persistent and scalable. My first thought is that each row has a "sequence" field indicating the display sequence. By default, the value should be same as id. When selecting data from database for display, the rows are sorted ascending on sequence instead of id.
If sequence is changed, then it is updated to new value. The result is that it may involves a lot of changes in other rows. Taking example above, originally the table is like this:
|id | sequence |
|0 | 0 |
|1 | 1 |
|2 | 2 |
|3 | 3 |
Now, after drag row with id 3 to first. Its sequence is updated to 0. At the same time, row with id 0, 1, 2 should also be updated.
|id | sequence |
|0 | 1 |
|1 | 2 |
|2 | 3 |
|3 | 0 |
I'm afraid this approach will make re-sequence cost a lot resource and not scalable. So, I suppose the sequence can be intiialized by multiplying id with K(say, 10). This leaves gaps between sequence value for insertion. However, the gap can still consumed up if K+1 rows are moved to this gap.
|id | sequence |
|0 | 0 |
|1 | 10 |
|2 | 20 |
|3 | 30 |
This seems a common problem to database design. Anybody has better idea to achive this?