14

Is it possible to reseed an auto increment column in a SQLite database, and if so, how is this done?

ie. The equivalent of DBCC CHECKIDENT ('MyTable', RESEED, 1) in SQL Server.

Mun
  • 14,098
  • 11
  • 59
  • 83

3 Answers3

24

In SQLite there is a table named SQLITE_SEQUENCE, which tracks the largest RowId value that a table has. You can do insert, updates and deletes on this table. For example, to mimic similar functionality as the TRUNCATE TABLE statement SQL Server you could something like:

DELETE FROM MyTableName;
DELETE FROM SQLITE_SEQUENCE WHERE NAME = 'MyTableName';

In the above example all data from MyTableName is removed, and the auto increment rowid is reset by removing the value from the SQLITE_SEQUENCE table. See the documentation for AUTOINCREMENT for more information.

dialex
  • 2,706
  • 8
  • 44
  • 74
Garett
  • 16,632
  • 5
  • 55
  • 63
  • Thanks, that worked perfectly. Just had to add a semicolon at the end of each line. – Mun Jun 26 '10 at 16:13
6
DELETE 
FROM MyTableName

select *
from SQLITE_SEQUENCE

update SQLITE_SEQUENCE 
set seq = 0
where name ='MyTableName'
valverij
  • 4,871
  • 1
  • 22
  • 35
Umesh V
  • 131
  • 1
  • 5
0

Alternatively you could export a SQL file from the SQLite database. Then edit the generated SQL file and update the appropriate entries to the desired IDs or delete the INSERT statements. After this create a new empty database and seed it with the adjusted SQL file. The highest ID + 1 will then be the ID for a new entry...

With this way you can decide, which entries to keep and which entries should be removed as a non-destructive or even a more flexible approach.

For me it worked - clean and easy. ;)

SiL3NC3
  • 690
  • 6
  • 29