Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to upsert into a table without creating new rows

Imagine I have a set of key-value data from a primary key to values:

id foo
1 abc
2 def
3 ghj

… that need to be updated in a table.

And I want to update all of these in one query. Naturally, upserts come to mind, which works quite well:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

INSERT INTO my_table (id, foo) VALUES ((1, 'abc'), (2, 'def'), (3, 'ghj')) 
ON CONFLICT (id) DO UPDATE SET foo = excluded.foo;

This works fine, but what if I don’t actually want to insert the row with id=3 when it doesn’t already exist in the table my_table?

>Solution :

I don’t see why you would need an INSERT at all if you just want to UPDATE the rows?

update my_table 
  set foo = v.foo 
from ( 
  VALUES (1, 'abc'), (2, 'def'), (3, 'ghj')
) as v(id, foo)
where v.id = my_table.id;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading