How to UPSERT (MERGE, INSERT … ON DUPLICATE UPDATE) in PostgreSQL?

前端 未结 6 1281
灰色年华
灰色年华 2020-11-21 05:42

A very frequently asked question here is how to do an upsert, which is what MySQL calls INSERT ... ON DUPLICATE UPDATE and the standard supports as part of the

6条回答
  •  醉话见心
    2020-11-21 06:14

    Here are some examples for insert ... on conflict ... (pg 9.5+) :

    • Insert, on conflict - do nothing.
      insert into dummy(id, name, size) values(1, 'new_name', 3)
      on conflict do nothing;`  
      
    • Insert, on conflict - do update, specify conflict target via column.
      insert into dummy(id, name, size) values(1, 'new_name', 3)
      on conflict(id)
      do update set name = 'new_name', size = 3;  
      
    • Insert, on conflict - do update, specify conflict target via constraint name.
      insert into dummy(id, name, size) values(1, 'new_name', 3)
      on conflict on constraint dummy_pkey
      do update set name = 'new_name', size = 4;
      

提交回复
热议问题