iossqlobjective-csqlitefmdb

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


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)

Solution

  • 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];