Manage MAX_ID and auto_increment value

In some strange cases, I experienced a lost of synchronization between the auto-increment id and the and the sequence which manage the auto-increment.

Here is a way to inspect and alter auto-increment value:


$># select MAX(id) FROM table_name;
 max 
-----
 957587
(1 row)

$># SELECT nextval('table_name_id_seq');
 nextval 
---------
  957398
(1 row)

$># ALTER SEQUENCE table_name_id_seq RESTART WITH 957588;
ALTER SEQUENCE

Notes

The sequence should be set with the max(id)+1 value. Obviously, you should be sure no one interact with this table during this sequence.

Leave a Reply

Your email address will not be published. Required fields are marked *