0
votes

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

1 Answers

1
votes

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.