Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql wrong auto-increment for serial

I have a problem on postgresql which I think there is a bug in the postgresql, I wrongly implement something.

There is a table including colmn1(primary key), colmn2(unique), colmn3, ...

After an insertion of a row, if I try another insertion with an existing colmn2 value I am getting a duplicate value error as I expected. But after this unsuccesful try, colmn1's next value is incremented by 1 although there is no insertion so i am getting rows with id sequences like , 1,2,4,6,9.(3,5,6,7,8 goes for unsuccessful trials).

I need help from the ones who can explain this weird behaviour.

This information may be useful: I used "create unique index on tableName (lower(column1)) " query to set unique constraint.

like image 660
woryzower Avatar asked Dec 16 '22 19:12

woryzower


1 Answers

See the PostgreSQL sequence FAQ:

Sequences are intended for generating unique identifiers — not necessarily identifiers that are strictly sequential. If two concurrent database clients both attempt to get a value from a sequence (using nextval()), each client will get a different sequence value. If one of those clients subsequently aborts their transaction, the sequence value that was generated for that client will be unused, creating a gap in the sequence.

This can't easily be fixed without incurring a significant performance penalty. For more information, see Elein Mustein's "Gapless Sequences for Primary Keys" in the General Bits Newsletter.

like image 115
Sjoerd Avatar answered Dec 18 '22 09:12

Sjoerd