Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres - ON CONFLICT - HOW to know if an UPDATE occurred instead of an INSERT [duplicate]

Tags:

I have a table

CREATE TABLE foo (     f0 int,     time_stamp timestamp,     CONSTRAINT foo_pk PRIMARY KEY (f0) ) 

I need to write to this table in high volumes, so performance is key. Sometimes, I will write a record that has an existing value for f0 and will just update the time_stamp to the current time. For this I use an ON CONFLICT..DO UPDATE clause.

The problem is that I need to know whether an INSERT has occurred or an UPDATE.

I though on using a second is_update column. When inserting, insert false and

`ON CONFLICT .. DO UPDATE set is_update=true` 

Then use RETURNING is_update to get what I want. The issue with that is the introduction of an additional column that is not related to the data itself.

like image 747
Sagi Avatar asked Mar 30 '16 15:03

Sagi


People also ask

What is needed for an insert on conflict update to work?

You must have INSERT privilege on a table in order to insert into it. If ON CONFLICT DO UPDATE is present, UPDATE privilege on the table is also required. If a column list is specified, you only need INSERT privilege on the listed columns.

What is upsert in PostgreSQL?

The UPSERT statement is a DBMS feature that allows a DML statement's author to either insert a row or if the row already exists, UPDATE that existing row instead. That is why the action is known as UPSERT (simply a mix of Update and Insert).

What is upsert mode?

The UPSERT option is the combination of 'Update' and 'Insert' which means that it will check for the records that are inserted or updated.

What is xmin and xmax in PostgreSQL?

When a row is created, the value of xmin is set equal to the ID of the transaction that performed the INSERT command, while xmax is not filled in. When a row is deleted, the xmax value of the current version is labeled with the ID of the transaction that performed DELETE.


1 Answers

Using two columns for timestamps is common practice. A creation_timestamp column would be set once, on insertion. While an update_timestamp would keep the last overriding update's timestamp to that record.

On each "upsert", you may check if the update_timestamp wasn't set already.

INSERT INTO foo (f0, creation_timestamp) VALUES (1, NOW()) ON CONFLICT (f0) DO UPDATE SET f0=EXCLUDED.f0, update_timestamp=NOW() RETURNING update_timestamp IS NULL 
like image 135
Jonathan Shemer Avatar answered Sep 21 '22 13:09

Jonathan Shemer