Bobby Meyer
developer/designer
postgresql | rails | ruby
Resetting PostgreSQL pk_sequences in Rails
March 6, 2021I have recently been working on a project that required transferring a large amount of data to a new PostgreSQL database with a dissimilar schema. I needed to import these records with their primary keys intact. Because of this, the primary key sequence was no longer in sync with the values in the database, and attempting to create new records can lead to this error:
To solve this, you need to reset the pk_sequence to the max value in the existing data. You can do this for a single table in the console by running:
More efficiently, you can do this for all tables with the following command.
back to posts