Sequence desynchronization
In today’s subject, I am going to present a classic problem when dealing with databases that use sequences. It’s about “Sequence desynchronization”.
Let start by defining a sequence. A sequence is a database feature that creates unique values by incrementing the old ones. It is important to emphasize that multiple transactions cannot get the same sequence value.
Get Anass Guendef’s stories in your inbox
Join Medium for free to get updates from this writer.
Sequence desynchronization, happens usually when database backup or restore fails to set sequences, when we set the sequence value incorrectly, or when we specify the id’s value manually.
When Sequence desynchronization occurs in PostgreSQL, it returns “duplicate key value violates unique constraint” error.
To solve this problem in PostgreSQL, we need to set the values of desynchronized sequences using the max(id) of concerned tables.
You can also fix all the sequences by constructing the query above for all the sequences in database.
All you need to do after that, is executing the resulting script.
It’s important to mention that the sequence must follow the PostgreSQL’s notation :
table-name_column-name_seq








