I want to keep a logical auto-increment in the ID field.
It is defined as SERIAL, but as soon as I delete a row (ex:15) and later insert a new one, the ID becomes 16 (so, it jumps from 14 to 16). What's the best way to handle that?
I want to keep a logical auto-increment in the ID field.
It is defined as SERIAL, but as soon as I delete a row (ex:15) and later insert a new one, the ID becomes 16 (so, it jumps from 14 to 16). What's the best way to handle that?
The best way to handle that? That's easy. Ignore this non-problem.
The serial
data type is guaranteed to put in an auto incrementing value. It does not guarantee much else. So, gaps are allowed, and they do appear -- for instance, as a result of deletes. This is a good thing. The primary purpose of serial columns to create primary keys. A primary key uniquely identifies each row and the integer data type is convenient for joining tables together. No reason to change a value along the way.
If you want an auto-incremented sequential value, then get what you want on output using row_number()
:
select t.*,
row_number() over (order by id) as MySequentialValueWithNoGaps
from table t