Apologies if the title doesn't communicate the question properly.
If I have a Postgres table called Person with the following columns and data:
name | age | order |
John | 42 | 1 |
Sam | 27 | 2 |
Phil | 19 | 3 |
The order column is a Float that determines the order by which the client should display a list of persons.
Is there an optimal performant way to insert a Person with an existing order but delegating the DB to autoincrement the values in the order column? If so, how?
For example, if I insert a new person (Emma, 56, 2) I want the result to be
name | age | order |
John | 42 | 1 |
Sam | 27 | 3 |
Phil | 19 | 4 |
Emma | 56 | 2 |
Note Sam and Phil now have their orders incremented.
Possible solution: I can take advantage of float and get the average of the previous order value and current order. So in the above example, it would be 1 (for John) + 2 (for Emma in the insert) / 2. The new order for Emma will be 1.5 which fits nicely as shown below:
name | age | order |
John | 42 | 1 |
Sam | 27 | 2 |
Phil | 19 | 3 |
Emma | 56 | 1.5 |
But this requires multiple DB calls hence the question.
Edit: While I went with George Joseph's answer in the final implementation, the correct answer that actually answered the question was clamp's. Hence I marked his answer as accepted.