2

None of the other questions which address this error seems to work for me. My query is:

IF NOT EXISTS (SELECT 1 FROM Configuration WHERE key = 'CookieCount')
BEGIN
  INSERT INTO Configuration (key, value)
  VALUES ('CookieCount', '0')
END

and my error message is: "could not prepare statement (1 near "IF": syntax error)"

I have this working in Postgres: http://sqlfiddle.com/#!15/b14ef/2/0 But this does not work in SQLite and I need it to work with both.

Nodeocrat
  • 816
  • 2
  • 14
  • 29
  • 2
    SQLite doesn't have a procedural SQL system like `IF` and `BEGIN`. For this, though, you can probably use `INSERT ... SELECT` with a `WHERE` condition that checks if the key exists or not. – Colonel Thirty Two Oct 07 '15 at 19:37
  • The code as shown in your question won't run in Postgres either (and it's not the code you have in the SQLFiddle). –  Oct 07 '15 at 19:38

2 Answers2

3

SQLite doesn't have an IF operator like that, at all. Nearest thing is the CASE... http://www.sqlite.org/lang_expr.html#case, but that doesn't really apply in your situation.

The answer in "Insert if not exists" statement in SQLite applies here, as an insert-if-not-exists statement.

Community
  • 1
  • 1
Graham Perks
  • 23,007
  • 8
  • 61
  • 83
3

Try to use something like this instead IF statement :

INSERT INTO Configuration (key, value) 
SELECT 'CookieCount', '0' 
WHERE NOT EXISTS(SELECT 1 FROM Configuration WHERE key = 'CookieCount');
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116