Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite 'IF NOT EXISTS' syntax error [duplicate]

Tags:

sql

sqlite

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.

like image 585
Nodeocrat Avatar asked Jan 17 '26 03:01

Nodeocrat


2 Answers

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');
like image 93
Roman Marusyk Avatar answered Jan 19 '26 17:01

Roman Marusyk


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.

like image 32
Graham Perks Avatar answered Jan 19 '26 17:01

Graham Perks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!