views:

27

answers:

1

I'm using SQLite to maintain a database which contains, among other things, a table with paths. The CREATE statement for the table looks like this

CREATE TABLE path (id INTEGER PRIMARY KEY AUTOINCREMENT,
                   name TEXT,
                   UNIQUE(name));

I'm looking for a short way to say 'insert this given path into the path table and give me the id it was assigned, or just give me the id in case it existed already' in SQL.

Right now, I'm doing this with multiple SQL statements (pseudocode ahead):

unsigned int getIdForPath(p) {
  result = exec("SELECT id FROM path WHERE name='$p';");
  if result.empty {
    exec("INSERT INTO path VALUES(NULL, '$p');");
    result = exec("SELECT last_insert_rowid() FROM path;");
  }
  return result.toInt();
}

So, I'm first trying to look up the id; if it doesn't seem to exist, I add a new entry and finally do another SELECT to get the most recently used id. This seems a bit clumsy and possibly inefficient.

Is there any more compact and/or efficient way to implement this logic?

UPDATE: The common case is that the entry does exist already, so the initial SELECT in the above pseudo code will find a result in most of the cases.

+1  A: 

You can do it with two steps by using INSERT OR IGNORE to insert the value if it does not already exist and than select id of the element.

Giorgi
True! However, I should've been more precise in my question. The common case is that the value *does* exist already. Hence, using INSERT OR IGNORE followed by SELECT will do two queries in any case whereas the pseudocode in the question will do just one query in the majority of cases. Of course you couldn't know this when you answered, so +1 to you for providing a shorter solution than mine. :-)
Frerich Raabe
If the value will already exist in majority of cases then your code is already efficient.
Giorgi
@Giorgi: That's good to know; still, is it possible to have an equally (or more) efficient solution which is shorter than what I wrote? Maybe some clever nested SQL query or so?
Frerich Raabe
Accepting this answer; I guess that you are right - if the common path is that the value exists already, then a simpl SELECT is as efficient as it gets.
Frerich Raabe