DEV Community

Drew Bragg
Drew Bragg

Posted on

4 1

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!

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay