As we learn more about the iPhone APIs we do a lot of web searching and reading of documentation. One question we had a hard time finding an answer to was how do we find the id (primary key) of the row we just inserted?

Our table has an auto-increment primary key field named id and we wanted to store that in our object after we inserted the row, but our web searches were not providing us an answer! Without knowing the terminology used by sqlite3 we were having real problems finding a solution. A little frustrated, we dug directly into the sqlite3 docs and found the answer. We figured we should post it here in hopes that if you have the same problem you’ll actually be able to find it when searching the web.

sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);


NSString* sql = @"insert into myTable (Title, Description) values ('My Title', 'My Description')";
sqlite3 *db;
sqlite3_open(myDataFilePath, &db);
char* errorMsg;
sqlite3_exec(db, [sql UTF8String], NULL, NULL, &errorMsg);
int primaryKeyId = sqlite3_last_insert_rowid(db);

How to get the auto-increment primary key after inserting a record

Leave a Reply

Your email address will not be published. Required fields are marked *