i have a table "test" with primary keys on "id & "lang"
╔════╦══════╦══════╦═══════╗
║ id ║ lang ║ test ║ test2 ║
╠════╬══════╬══════╬═══════╣
║ 1 ║ zh ║ lol3 ║ lol4 ║
║ 1 ║ en ║ lol ║ qsdf ║
╚════╩══════╩══════╩═══════╝
and i want to do insert or update but since you cannot do IF statement im left out with INSER OR REPLACE INTO
when i run my query :
INSERT OR REPLACE INTO test (id,lang,test) VALUES (1,'en','zaki')
i get this
╔════╦══════╦══════╦════════╗
║ id ║ lang ║ test ║ test2 ║
╠════╬══════╬══════╬════════╣
║ 1 ║ zh ║ lol3 ║ lol4 ║
║ 1 ║ en ║ zaki ║ <null> ║
╚════╩══════╩══════╩════════╝
It deletes the record and inserts a new one with available data ( like the documentation of sqlite states. ) But i want to keep the value of test2 ( but without knowing i need to keep the value of test2 ) i only know which value to replace not which to keep. is it possible to not lose the data i pass through (in 1 query).
It would seem that your primary key is on
(id, lang)
and your query found an existing record withid = 1, lang = 'en'
and did aREPLACE
on it using the data you specified.SQLite has no UPSERT, and it is designed to be embedded in some program. You are supposed to implement the IF in whatever language you are using there:
This could be optimized a little bit with INSERT OR IGNORE:
Most straightforward would be to use two queries conditionally, such as
INSERT OR IGNORE
followed byUPDATE
conditionally, but if you insist on single query, you can try a subquery:Example: