Stephen Gilmore

🛠️ Fix an out of sync PostgreSQL Sequence

Programming December 5th, 2023 1 minute read.

"Someone" accidentally left off updating the sequence when importing their production PostgreSQL data into a test database. Not wanting to dump all the data and completely start over again, I found a way to just update the sequence.

All of these commands are/were done in the psql terminal.

/* Check the count of records and the values in the sequence. */
SELECT MAX(id) FROM "posts";
SELECT COUNT(*) FROM "posts";
SELECT nextval('posts_id_seq');
SELECT currval('posts_id_seq');


/* Update the sequence. */
SELECT setval('posts_id_seq', max(id)) FROM posts;

This and a whole lot of other examples and answers come from this stackoverflow post.