I have a following table:
| folderId | folderPath |
|---|---|
| 1 | "C:\Users\obama" |
| 2 | "C:\Users\biden" |
Here, folderId is an autoincrement key. Now, insertion into the table has following steps: a)check if given folderPath exists in the table or not. b)If given folderPath exists then return folderId of that path. c)If folderPath doesn't exist then insert that folderPath into the table and return its folderId(last inserted rowId)
I want to add above steps in a single SQlite query for better performance. I am new to sqlite so any help would be greatly appreciated. Thanks
I tried to create a single sqlite query for the steps mentioned above. My expectation is to have a single query for better performance.
In short you cannot accomplish all the above in a single query. SQLite can only process a single statement at a time. You will always require 2 statements:-
One to insert or not and another to query the table to obtain the id (or vice-versa i.e. to query and then insert or not).
However, the
SQLiteDatabase'sinsertmethod does, under the cover, perform both the insert and obtains the rowid or an alias thereof (which the folderId column is according to your question in that the id is generated).Furthermore, the
SQLiteDatabase'sinsertmethod usesINSERT OR IGNORE ..... Thus not failing if there is a UNIQUE constrain conflict.For these reasons it is probably easiest to utilise the
SQliteDatabase's convenienceinsertmethod along with having a UNIQUE index on the folderPath column.As for performance you should look into wrapping the inserts, if doing more than one at a time, within a single transaction.
The following is a working demonstration based upon the information available in your question:-
DBOpenHelper (of particular note is the
insertOrNotFolderReturningFolderIdmethod)To actually demonstrate then the following activity code:-
Results output to the log:-
i.e. only the 3 rows exists (last section) out of the 7 attempted inserts from the testlist but the respective folderid has been returned (first section)