Reset PostgreSQL auto increment value in Rails
I've been involved in writing a rake task to migrate an old database schema to a similar but new schema in a Rails project. The new schema was similar enough that we could carry across all the primary keys from the old tables, and it saved a lot of time to re-use them. However, the problem with doing this is that the auto increment sequence does not get updated when you add a value - you have to manually reset it.
This can be done in Rails, but only by using raw SQL. The code to execute is:
If you want to run this for all tables (as we did after our migration script completed), you can loop through all the available tables and get the most recent ID: