Question

Postgres Database sequence out of sync

My database table sequencing has gone off sync, I’m getting PK violation errors on inserts. I’ve tried restarting the sequnce it but rolls back to the erroneous sequence. Please help.


Submit an answer


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Bobby Iliev
Site Moderator
Site Moderator badge
June 15, 2023

Hi there,

You could give the following a try:

  • Take a backup of your database so that you could revert to it in case anything goes wrong!
  • Login to psql and run the following
  • Get the max value from your table:
SELECT MAX(id) FROM your_table;
  • Then run the following, which should be higher than the last result:
SELECT nextval('your_table_id_seq');
  • If it’s not higher, run this set the sequence last to your highest id.

Make sure to run a quick pg_dump first!

BEGIN;
-- protect against concurrent inserts while you update the counter
LOCK TABLE your_table IN EXCLUSIVE MODE;
-- Update the sequence
SELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false);
COMMIT;

Remember to be very careful when manipulating sequences and other database objects, as mistakes can lead to data corruption or loss.

Let me know how it goes!

Best,

Bobby

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel