Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Predict next auto-inserted row id (SQLite)

Tags:

I'm trying to find if there is a reliable way (using SQLite) to find the ID of the next row to be inserted, before it gets inserted. I need to use the id for another insert statement, but don't have the option of instantly inserting and getting the next row.

Is predicting the next id as simple as getting the last id and adding one? Is that a guarantee?

Edit: A little more reasoning... I can't insert immediately because the insert may end up being canceled by the user. User will make some changes, SQL statements will be stored, and from there the user can either save (inserting all the rows at once), or cancel (not changing anything). In the case of a program crash, the desired functionality is that nothing gets changed.

like image 289
foobar Avatar asked Sep 20 '08 03:09

foobar


People also ask

Does SQLite have AUTO increment?

SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto increment. The keyword AUTOINCREMENT can be used with INTEGER field only.

How does AUTO increment work in SQLite?

AUTOINCREMENT guarantees that automatically chosen ROWIDs will be increasing but not that they will be sequential. Because AUTOINCREMENT keyword changes the behavior of the ROWID selection algorithm, AUTOINCREMENT is not allowed on WITHOUT ROWID tables or on any table column other than INTEGER PRIMARY KEY.

When you insert a new row into a SQLite database it automatically generates a value for?

If you don't specify the rowid value or you use a NULL value when you insert a new row, SQLite automatically assigns the next sequential integer, which is one larger than the largest rowid in the table. The rowid value starts at 1.

Does SQLite insert return ID?

SQLite has a special SQL function – last_insert_rowid() – that returns the ID of the last row inserted into the database so getting the ID of a new row after performing a SQL insert just involves executing the last_insert_rowid() command.


1 Answers

Try SELECT * FROM SQLITE_SEQUENCE WHERE name='TABLE';. This will contain a field called seq which is the largest number for the selected table. Add 1 to this value to get the next ID.

Also see the SQLite Autoincrement article, which is where the above info came from.

Cheers!

like image 124
Greg J Avatar answered Oct 07 '22 18:10

Greg J