Postgresql Return Whether Upsert Query INSERTed a New Row or UPDATEd one

53 views Asked by At

I want to know if an upsert/"on conflict do update" query inserted a new row or only updated one.

There is a few ways that kind of work but they don't feel correct Here is my current query:

INSERT INTO mytable
  (id, mycolumn)
VALUES
  (123, 'abc')
ON CONFLICT DO UPDATE
  SET mycolumn = 'xyz'
RETURNING (
    select max(id)
    from mytable
  ) = id as inserted
1

There are 1 answers

0
meme-lord On

This question came up on related and appears to be the correct answer Differentiate inserted and updated rows in UPSERT using system columns

RETURNING (xmax = 0) AS inserted