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

前端 未结 6 1443
灰色年华
灰色年华 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 05:56

    I am trying to contribute with another solution for the single insertion problem with the pre-9.5 versions of PostgreSQL. The idea is simply to try to perform first the insertion, and in case the record is already present, to update it:

    do $$
    begin 
      insert into testtable(id, somedata) values(2,'Joe');
    exception when unique_violation then
      update testtable set somedata = 'Joe' where id = 2;
    end $$;
    

    Note that this solution can be applied only if there are no deletions of rows of the table.

    I do not know about the efficiency of this solution, but it seems to me reasonable enough.

提交回复
热议问题