Question

I have a table in my database with one field declared as

_id integer primary key

There is no AUTOINCREMENT.

Here i have a doubt about how rowid will be updated during insert after a delete. what i observed is

  1. if the last row id is x and it is deleted, the next row inserted gets id x.

But if i delete some other rows with id < x and then insert a new row the rowid of the newly inserted row is x+1 .

Please confirm is my observation right ( rowid reused only if the last rows are deleted and not in between rows. )

I saw the explanation for AUTOINCREMENT. I want to know the behaviour when no AUTOINCREMENT is set

Was it helpful?

Solution

The AUTOINCREMENT keyword is not required for SQLite tables to generate primary key values automatically.. what ever you add to the database will be added as the last row...so if u delete last row(x).. new element will be added at x position.. if you delete from middle or not.. new element on addition will go to x+1 position...

on using auto increment.. if you delete last element at x position next id x+1 will be generated by autoincrement algorithm.. makin the next addition at x+1 position..

OTHER TIPS

Without an autoincrement set, the row would be an alias for the ROWID...

This is what the FAQ says:

If no ROWID is specified on the insert, or if the specified ROWID has a value of NULL, then an appropriate ROWID is created automatically. The usual algorithm is to give the newly created row a ROWID that is one larger than the largest ROWID in the table prior to the insert. If the table is initially empty, then a ROWID of 1 is used. If the largest ROWID is equal to the largest possible integer (9223372036854775807) then the database engine starts picking positive candidate ROWIDs at random until it finds one that is not previously used. If no unused ROWID can be found after a reasonable number of attempts, the insert operation fails with an SQLITE_FULL error. If no negative ROWID values are inserted explicitly, then automatically generated ROWID values will always be greater than zero.

The normal ROWID selection algorithm described above will generate monotonically increasing unique ROWIDs as long as you never use the maximum ROWID value and you never delete the entry in the table with the largest ROWID. If you ever delete rows or if you ever create a row with the maximum possible ROWID, then ROWIDs from previously deleted rows might be reused when creating new rows and newly created ROWIDs might not be in strictly ascending order.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top