Context
I have an SQL table containing items.
id name order
==============
1 book 3
2 table 1
3 chair 2
4 bag 4
So as we can see, the items are sorted in this order:
- table
- chair
- book
- bag
Question
Given a form where a user can reorder an item by selecting another item as reference and a placement (before or after), what is the most optimal algorithm to reorder items so that the order is re-generated from 1 to N (where N is the amount of items)?
By "optimal" I mean consuming the least amount of resources (so the O complexity should be the closest possible to O(N)).
If possible, provide a pseudo-code algorithm (if you prefer writing in your prefered programming language it's fine for me as well).
Example
Here is a picture with the form I intent to use if you need a mental model to better grasp on this challenge:
In action, given this dataset
id name order
==============
1 book 3
2 table 1
3 chair 2
4 bag 4
Case 1: the user wants to place the bag before the table. The result will be:
id name order
==============
1 book 4
2 table 2
3 chair 3
4 bag 1
Case 2: Keeping this dataset, the user now decides to place the table after the chair. The result will be:
id name order
==============
1 book 4
2 table 3
3 chair 2
4 bag 1
Case 3: this time the user would like to place the book before the chair. The result will be:
id name order
==============
1 book 2
2 table 4
3 chair 3
4 bag 1
Case 4: the user request to put the bag before the chair. The result will be:
id name order
==============
1 book 1
2 table 4
3 chair 3
4 bag 2

There is not enough space in the comments, so I add one possible solution. This assumes you just use the order column to sort your query and the number itself is of no significance.
Instead of having only the numbers 1 to N in the order column, we can use bigger numbers with gaps. E.g. 100, 200, 300, ... initially. This lets us insert an element before/after another element just by updating a single row.
If we always insert an element in the middle of the gap, then we can calculate the number of modifications you can make in the worst case before having a clash. If there is a clash you need to normalize the order column again before you can do the modification.
Lets have the same initial gap betwen all elements and order[i] is the ith value of the sorted order column, then inital gap size
G = order[i + 1] - order[i] - 1. We can calculate the required gap size to ensure we can do M modifications without having to normalize as follows:G(0) = 0 and G(M + 1) = 2 * G(M) + 1. So G needs to be a little bit greater than 2^M. We also need to consider that if we put numbers at the end or the beginning with a gap size of G, then the minimum/maximum of the order column is shrinking/growingG + 1per modification in the worst case.Basically the same trick was used by old programmers for languages where you had to number the lines yourself. With the gaps you had space to do modifications later without having to renumber everything.