I have a list of objects (called “Phases”) that I’m storing in a db table.
I need to maintain the order of the Phases in the list. I’m wondering what’s a good way to model this?
I’m thinking I’ll give the Phase object an “int sequence” attribute that dictates the order and since it’s persisted to the table, I can read them back in order. The only problem I see is that when I change the order of the sequence, I have to recalculate all the sequence values for every Phase in the list. Example, swap the positions of #2 and #3 causes everything after #3 (say up to #1000) to have to be updated in the db too.
Is there an easier way to model this that I have not considered?
I’d do it the way you described.
Yes if you want to insert new values, then if you’ve used consecutive rank values then you need to bump existing values, say
It follows that you can’t usually make the rank column be unique because you don’t know what order the UPDATE will be processed in.
If you’re accessing the database programmatically, you could allow non-consecutive rank values, so existing ranks only need to be bumped when there isn’t a gap in the numbering sequence.
Also, if you are using a row/page-based database, you could consider taking rankings out to a separate table which just has the ID of the main record, and the rank value. Then if you did need to make mass updates to rankings, you wouldn’t be having to read and write entire main records, but just tiddly records containing a couple of integers.