Another approach is INSERT ... SELECT ... WHERE ... EXISTS [or not] (SELECT ...);
I do this all the time and I also use the jklemmack suggestion. And I do this for other purposes too, for example, for JOINs in UPDATE (which does not support SQLite3).
For instance:
CREATE TABLE t(id INTEGER PRIMARY KEY, c1 TEXT NOT NULL UNIQUE, c2 TEXT); CREATE TABLE r(c1 TEXT NOT NULL UNIQUE, c2 TEXT); INSERT OR REPLACE INTO t (id, c1, c2) SELECT t.id, coalesce(r.c1, t.c1), coalesce(r.c2, t.c2) FROM r LEFT OUTER JOIN t ON r.c1 = t.c1 WHERE r.c2 = @param;
WHERE there is a condition that you would have in your IF. JOIN in SELECT provides a JOIN that SQLite3 does not support in UPDATE. INSERT OR REPLACE and using t.id (which can be NULL if the string does not exist in t) together provide the THEN and ELSE bodies.
You can apply it again and again. If you have three statements (which cannot be combined into one) in the THEN part of IF, you will need to have three statements with the IF clause in your WHERE clause.
source share