0

Im using sqlite db in a sample rails application. From my users table, i have cleared all records using User.delete_all. But now whenever i insert a new record in the table using User.create, the id is starting at a value which is one more than the id of the last record which was there in the table. For example, if my table had 5 records and i cleared all, then when i do User.create, its starting at id 6. Is there any way i can make the id start from 1 again ?

Thank You

2
  • 1
    I believe you'd to do a rake db:reset or similar to clear the index. Or, you could use this: sqlite.org/lang_reindex.html. However, why do you need to do this?? Dec 15, 2012 at 12:21
  • Fixed by running the following at rails console : ActiveRecord::Base.connection.execute("DELETE from sqlite_sequence where name = 'users'")
    – jimcgh
    Dec 15, 2012 at 12:26

2 Answers 2

5

Similar question : How to reset a single table in rails? . We can run the following at rails console to reset id column to 1 for a sqlite table

ActiveRecord::Base.connection.execute("DELETE from sqlite_sequence where name = '<table_name>'") 
3

You seem to have autoincrement turned on for the id column. Sqlite handles these values in an internal table called sqlite_sequence. You could reset the id for a particular autoincrement-enabled table by querying:

UPDATE "sqlite_sequence" SET "seq" = 0 WHERE "name" = $YOURTABLENAME

However, this is not a good idea because the autoincrement functionality is intended to be used in a way that the user does not influence its algorithm. Ideally, you should not care about the actual value of your id but consider it only as a unique identifier for a record.

1
  • Thanks for the reply :). An alternate way would be to use the active record api from rails console, which is what i did.
    – jimcgh
    Dec 15, 2012 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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