23

The following works in the Rails 3 console to reset Postgres sequences:

ActiveRecord::Base.connection.reset_pk_sequence!('menucontrols')
ActiveRecord::Base.connection.reset_pk_sequence!('statuscodes')
ActiveRecord::Base.connection.reset_pk_sequence!('wostatuses')
ActiveRecord::Base.connection.reset_pk_sequence!('taskstatuses')
ActiveRecord::Base.connection.reset_pk_sequence!('priorities')
ActiveRecord::Base.connection.reset_pk_sequence!('actcodes')

Is there a command that would reset ALL of them instead of having to do each one individually?

Thanks for the help!

2 Answers 2

59

This is easier

ActiveRecord::Base.connection.tables.each do |t|
  ActiveRecord::Base.connection.reset_pk_sequence!(t)
end
0
15

I found one way to do it from this posting: Reset PostgreSQL

I placed the following into seed.rb and ran rake db:seed

ActiveRecord::Base.connection.tables.each do |table|
  result = ActiveRecord::Base.connection.execute("SELECT id FROM #{table} ORDER BY id DESC LIMIT 1") rescue ( puts "Warning: not procesing table #{table}. Id is missing?" ; next )
  ai_val = result.any? ? result.first['id'].to_i + 1 : 1
  puts "Resetting auto increment ID for #{table} to #{ai_val}"
  ActiveRecord::Base.connection.execute("ALTER SEQUENCE #{table}_id_seq RESTART WITH #{ai_val}")
end
2
  • 1
    Tried doing the reset_pk_sequence! approach but ran into issues with it when I used Heroku Postgres VS my dev PG (with tables where it should have worked). Perhaps a result of a newer version of PG vs older version. Anyway, this approach did the job and even any errors. Very nice.
    – Nuclearman
    Jan 30, 2018 at 5:55
  • This is today's "You save my life!". Our DBA migrated data tables but forgot to rebuild seq
    – Hegwin
    Mar 24, 2021 at 7:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.