In Android, I created an SQLite database containing one table, which in turn has an auto-increment ID column.
Suppose I have 4 records. When I delete all of them, the next inserted record has the ID of a 5th one (4), but I need to insert this record starting again from the 1st position, i.e. 0.
How can I achieve this?
EDIT: Maybe I should make it clear that just inserting the rows with the correct id instead of manipulating the sequence number definitely is a better idea than the below method. If there’s no row with id=3 in the table, you can just insert with a fixed value in the id even in an AUTOINCREMENT table.
That said, if you’re really sure, you can set the auto increment value to any value using;
That is, if you want AUTOINCREMENT on the next insert on table ‘TableA’ to generate 5, you do;
Note that resetting
seqbehaves a bit different from what you may expect, it just means that the lowest id generated will be the greater ofseq + 1and themax id still in the table + 1.That is, if you delete all values >=5, you can reset the sequence value to 4 and have 5 generated as the next sequence number, but if you still have the id 10 in the table, the next number generated will be 11 instead.
Maybe I should point out the fact that I cannot find this exact behavior documented anywhere, so I’d not rely on the behavior for every future version of sqlite. It works now, it may not tomorrow.