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.
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.
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).
The UPSERT option is the combination of 'Update' and 'Insert' which means that it will check for the records that are inserted or updated.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With