Reset Postgres ID sequence in Rails
Drew Bragg

Drew Bragg @drbragg

About: Full Stack Dev && Single Dad && Board Game Geek && Hockey Player

Location:
Warrington, PA
Joined:
Feb 8, 2018

Reset Postgres ID sequence in Rails

Publish Date: Jun 18 '20
7 0

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!

Comments 0 total

    Add comment