How would I do “UPSERT” (INSERT OR UPDATE) into SQLite table when inserting multiple rows from another table.
I’ve tried:
INSERT INTO tab_name
SELECT * FROM tmp
ON CONFLICT(id)
DO UPDATE SET
val = excluded.val;
But it gives me:
syntax error near “DO”
What would be the correct and the most efficient way to achieve that?
Advertisement
Answer
You might have hit a documented trap called parsing ambiguity :
When the
INSERTstatement to which theUPSERTis attached takes its values from aSELECTstatement, there is a potential parsing ambiguity. The parser might not be able to tell if the"ON"keyword is introducing theUPSERTor if it is theONclause of a join. To work around this, theSELECTstatement should always include aWHEREclause, even if thatWHEREclause is just"WHERE true".)
So, does this work better?
INSERT INTO tab_name SELECT * FROM tmp WHERE true ON CONFLICT(id) DO UPDATE SET val = excluded.val;