Reset Postgres ID sequence in Rails

drbragg

Drew Bragg

Posted on June 18, 2020

Reset Postgres ID sequence in Rails

Today I had to restore backup data from one of our SQL dumps to my local development database. For one reason or another the table id sequences didn't reset after the restore. So I was getting errors in my terminal like this:

PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "track_events_pkey"
DETAIL:  Key (id)=(3673) already exists.
: INSERT INTO "track_events" ("track_session_id", "action", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" excluded from capture: DSN not set
Enter fullscreen mode Exit fullscreen mode

Manually resetting it is actually quite easy.

Hop into your rails console and run:

ActiveRecord::Base.connection.tables.each do |t|
  ActiveRecord::Base.connection.reset_pk_sequence!(t)
end
Enter fullscreen mode Exit fullscreen mode

I hope this helps someone else who runs into a similar issue!

💖 💪 🙅 🚩
drbragg
Drew Bragg

Posted on June 18, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Reset Postgres ID sequence in Rails
todayilearned Reset Postgres ID sequence in Rails

June 18, 2020