Postgres upsert: distinguish between new and updated rows [duplicate]

帅比萌擦擦* 提交于 2019-12-31 04:35:20

问题


I'm thinking of using PostgreSQL INSERT .. ON CONFLICT UPDATE functionality. Ideally I would be able to distinguish between which rows were successful inserted and which were updated. Is there a way to do it?


回答1:


You need an additional auxiliary column for this (updated in the example).

create table test (id int primary key, str text, updated boolean);
insert into test values (1, 'old', false);

insert into test values
    (1, 'new 1', false),
    (2, 'new 2', false)
on conflict (id) do
update set 
    str = excluded.str, updated = true
returning *;

 id |  str  | updated 
----+-------+---------
  1 | new 1 | t
  2 | new 2 | f
(2 rows)



回答2:


There is a way without adding a column to your table:

CREATE TABLE tbl(id int PRIMARY KEY, col int);
INSERT INTO tbl VALUES (1, 1);
INSERT INTO tbl(id, col)
VALUES (1,11), (2,22)
ON     CONFLICT (id) DO UPDATE
SET    col = EXCLUDED.col
RETURNING *, (xmax = 0) AS inserted;

Explanation:

  • Detect if the row was updated or inserted


来源:https://stackoverflow.com/questions/38613887/postgres-upsert-distinguish-between-new-and-updated-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!