Best way to get the ID of the last inserted row on SQLite

vdaubry picture vdaubry · May 3, 2011 · Viewed 19.9k times · Source

On iPhone, what's the best way to get the ID of the last inserted row on an SQLite Database using FMDB ?

Is there a better way rather than doing :

SELECT MAX(ID)

Answer

BoltClock picture BoltClock · May 3, 2011

If you can guarantee that your ID column is an auto-increment column, MAX(ID) is fine.

But to cover any case, there's a specialized SQLite function called LAST_INSERT_ROWID():

SELECT LAST_INSERT_ROWID();

In FMDB, you use the -lastInsertRowId method (which internally runs the above):

int lastId = [fmdb lastInsertRowId];