maxedison maxedison - 1 year ago 97
SQL Question

Retrieving ids of batch inserted rows in SQLite

I'm using SQLite's

to grab the last inserted row ID following a batch insert. Is there any risk of race conditions that could cause this value to not return the last id of the batch insert? For example, is it possible that in between the completion of the insert and the calling of
some other process may have written to the table again?

Answer Source

last_insert_rowid() returns information about the last insert done in this specific connection; it cannot return a value written by some other process.

To ensure that the returned value corresponds to the current state of the database, take advantage of SQLite's ACID guarantees (here: atomicity): wrap the batch inserts, the last_insert_rowid() call, and whatever you're doing with the ID inside a single transaction.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download