Detect if the row was updated or inserted

回眸只為那壹抹淺笑 提交于 2019-11-28 02:18:02

问题


I am doing an INSERT with ON CONFLICT to postgre using java. Is there any way to find out if the executeUpdate inserted the row or updated it?


回答1:


You can look at the system column xmax to tell the difference. It's 0 for inserted rows in this case.

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;

This is building on an undocumented implementation detail that might change in future releases (even if unlikely). It works for Postgres 9.5 and 9.6.

The beauty of it: you do not need to introduce additional columns.

Detailed explanation:

  • PostgreSQL Upsert differentiate inserted and updated rows using system columns XMIN, XMAX and others


来源:https://stackoverflow.com/questions/40878027/detect-if-the-row-was-updated-or-inserted

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