lI have a table with an ID column which is the Primary key and auto incremented. I have another column named ORDER that contains a number. This number is used to define the order in which the row data is displayed on a page.
When I delete a row, the ORDER column will have a gap and I would like to renumber the subsequent rows to remove the gap. ie:
I want to renumber the rows:
ID ORDER
1 1
2 2
4 3
5 4
When I insert a new row I want the ORDER row to be given the NEXT sequential number
The simplest way to do this would be to do a SELECT query and get all of the elements, ordered by ID. Then just go through and do an UPDATE on each one, changing the ORDER to an ever incrementing value.
However, there are two potentially better ways to do this:
If the ID and ORDER are always related, then why have order? Just arrange stuff based on ID.
When you remove a single row, you could do an UPDATE SET ORDER = ORDER - 1 WHERE ORDER > removedOrder.
If I knew more what you were doing with this I could help a bit more.
A better solution would be to not store the order in the database at all but to generate that field as you read the records. That way the order values are automatically updated when a record is deleted.