Report this

What is the reason for this report?

Postgres Database sequence out of sync

Posted on June 15, 2023

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.



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!

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.

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

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.