Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UPSERT for "INSERT INTO tab SELECT * FROM another_tab"

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?

like image 746
MaxU - stop WAR against UA Avatar asked Dec 10 '25 21:12

MaxU - stop WAR against UA


1 Answers

You might have hit a documented trap called parsing ambiguity :

When the INSERT statement to which the UPSERT is attached takes its values from a SELECT statement, there is a potential parsing ambiguity. The parser might not be able to tell if the "ON" keyword is introducing the UPSERT or if it is the ON clause of a join. To work around this, the SELECT statement should always include a WHERE clause, even if that WHERE clause 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;
like image 110
GMB Avatar answered Dec 12 '25 11:12

GMB



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!