SQLite: *prevent* PRIMARY KEY Value From Resetting After Delete All Rows
I have a SQLite table, with a few columns, including an 'ID' column which is INTEGER PRIMARY KEY. When I insert, this value increments as expected. However, when I delete all rows,
Solution 1:
If the AUTOINCREMENT keyword appears after INTEGER PRIMARY KEY, that changes the automatic ROWID assignment algorithm to prevent the reuse of ROWIDs over the lifetime of the database. In other words, the purpose of AUTOINCREMENT is to prevent the reuse of ROWIDs from previously deleted rows.
Solution 2:
What version of SQLite are you using? I am using SQLite version 3.8.11.1. Primary key values are not resetting.
Create table and insert some data
sqlite> create table test (id integer primary key autoincrement, name varchar(20));
sqlite> select * from test;
sqlite> insert into test (name) values ('hello1');
sqlite> insert into test (name) values ('hello2');
sqlite> select * from test;
id name
---------- ----------
1 hello1
2 hello2
sqlite> select * from sqlite_sequence;
name seq
---------- ----------
test 2
In an autoincrement column, sqlite keeps information of sequence in sqlite_sequence internal table that you can query also.
Delete data. Notice that sequence stays as-is.
sqlite> delete from test;
sqlite> select * from sqlite_sequence;
name seq
---------- ----------
test 2
sqlite> select * from test;
sqlite> insert into test (name) values ('world1');
sqlite> insert into test (name) values ('world2');
sqlite> select * from test;
id name
---------- ----------
3 world1
4 world2
sqlite> select * from sqlite_sequence;
name seq
---------- ----------
test 4
Based on this it appears that sequence numbers are staying as-is after deletion. I am using the autoincrement keyword.
Post a Comment for "SQLite: *prevent* PRIMARY KEY Value From Resetting After Delete All Rows"