Preface
Imagine that you have a set of tasks to accomplish today written down on a piece of paper, ordered by their importance. As the day goes on: you’ll mark some tasks as complete, maybe one task becomes extra important and you move it to the top of the list, or maybe you will discover a new task that needs done and add it to the bottom or middle of the list.
There is a hidden difficulty in keeping ordered data sets (like tasks ordered by importance or priority) in a traditional sql database. In this post I hope to explain well the decisions that I made while building a Flashcard app.
Available Strategies
Position as a Field
In this strategy, your table has a column that holds a position value. Any time you need to change the position of a single record, you will also need to update all records with higher/lower position.
- Pros:
- Reading an ordered sequence of records from the database is trivial and performant.
- Cons:
- Updating records in a way that keeps order is not trivial.
- Not as performant in large datasets (compared to Linked List strategy) as every change in position requires many record updates.
Use this strategy if the order of records will change very infrequently.
Non-Collapsing (Gapped)
Some developers out there will recommend leaving gaps between values in the position column. For example, if the first record is at position 0, then you should place the next record at position 9. In this manner, if you need to insert a new record between the first and second records, then you can insert it with position value = 4, and avoid having to update any other records.
In my opinion, leaving gaps between values is an anti-pattern. In reality, as the gaps start getting filled in, you’ll end up with the Collapsing strategy anyways. The only way to delay the inevitable is to create larger gaps. You, the developer, not only have to write the same code as the Collapsing strategy, but in addition you have to write additional logic for creating and managing gaps as values change.
- Pros:
- Record updates become cheap since you don’t necessarily need to update other records each time.
- Cons:
- More development effort.
- Gaps potentionally require larger datatypes to manage the same amount of records.
Collapsing
Instead of leaving gaps between position values, you can collapse empty space. If you have positions 1, 2, and 3 filled, and the user chooses to delete position 2, then the record in position 3 should change to become position 2.
- Pros:
- Position values represent what we humans refer to “1st position”, “2nd position” etc. And can be readily presented to the user.
- Cons:
- Retains the problem of every position change requiring many additional record upates.







