How to reseed an an auto increment column in a SQLite database?
Asked Answered
P

3

15

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.

Periclean answered 26/6, 2010 at 5:44 Comment(0)
M
25

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.

Microscopic answered 26/6, 2010 at 7:45 Comment(1)
Thanks, that worked perfectly. Just had to add a semicolon at the end of each line.Periclean
M
6
DELETE 
FROM MyTableName

select *
from SQLITE_SEQUENCE

update SQLITE_SEQUENCE 
set seq = 0
where name ='MyTableName'
Mute answered 7/7, 2012 at 19:6 Comment(0)
L
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. ;)

Loiretcher answered 23/11, 2021 at 17:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.