I want to update a row if it exists in the table else insert it in SQLite in single query. From SQLite documentation I found out that we can use REPLACE command for achieving this.
I want to know how to use REPLACE if there are two or more conditions:
Example:
If I have table TABLE1 with following records:
Name Type InitialValue FinalValue
A 1 20 40
B 2 23 50
A 3 40 60
C 3 54 70
Here Combination of Name and Type will be unique.
I want to set initialvalue = 50 and finalvalue = 90 where name = A and Type = 3 if it exists, else insert it.
I am using this command but it’s giving this error:
REPLACE INTO table1 (Name,Type,InitialValue,FinalValue) VALUES
(‘A’,3,50,90 ) WHERE Name=’A’ AND Type = 3 ;
Error is:
near “WHERE”: syntax error Unable to execute statement
How can I achieve my objective? Please help.
replace is just like insert, it just checks if there is duplicate key and if it is
it deletes the row, and inserts the new one, otherwise it just inserts
you can do this if there is for example unique index of (Name,Type) and if you type the following command
and there already exists a row with Name = ‘A’ and Type = 3 it will be replaced
http://www.sqlite.org/lang_createindex.html
EDIT:
a quick note – REPLACE always DELETES and then INSERTs, so it is never a very good idea to use it in heavy load because it needs exclusive lock when it deletes, and then when it inserts
some of the database engines have
sqlite 3 does not, but you can do try {} catch if insert fails
http://blog.client9.com/2007/11/sqlite3-and-on-duplicate-key-update.html
SQLite UPSERT – ON DUPLICATE KEY UPDATE