Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql, update if row with some unique value exists, else insert

I have a URLs table. They contain

(id int primary key, url character varying unique, content character varying, last analyzed date).

I want to create trigger or something(rule may be), so each time i make insert from my java program, it updates some single row if row with such URL exists. Else it should perform an Insert.

Please, can you provide a complete code in Postgresql. Thanks.

like image 473
Roman Lebedev Avatar asked Jun 21 '12 09:06

Roman Lebedev


People also ask

How do you insert if row does not exist Upsert in PostgreSQL?

There is a nice way of doing conditional INSERT in PostgreSQL: INSERT INTO example_table (id, name) SELECT 1, 'John' WHERE NOT EXISTS ( SELECT id FROM example_table WHERE id = 1 );

Does update insert in Postgres?

The idea is that when you insert a new row into the table, PostgreSQL will update the row if it already exists, otherwise, it will insert the new row. That is why we call the action is upsert (the combination of update or insert).

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 Postgres?

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).


2 Answers

This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671

This solution requires both an UPDATE and INSERT.

UPDATE table SET field='C', field2='Z' WHERE id=3; INSERT INTO table (id, field, field2)        SELECT 3, 'C', 'Z'        WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3); 

With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507

like image 178
Dave Halter Avatar answered Sep 21 '22 22:09

Dave Halter


If INSERTS are rare, I would avoid doing a NOT EXISTS (...) since it emits a SELECT on all updates. Instead, take a look at wildpeaks answer: https://dba.stackexchange.com/questions/5815/how-can-i-insert-if-key-not-exist-with-postgresql

CREATE OR REPLACE FUNCTION upsert_tableName(arg1 type, arg2 type) RETURNS VOID AS $$      DECLARE      BEGIN          UPDATE tableName SET col1 = value WHERE colX = arg1 and colY = arg2;          IF NOT FOUND THEN          INSERT INTO tableName values (value, arg1, arg2);          END IF;      END;      $$ LANGUAGE 'plpgsql';  

This way Postgres will initially try to do a UPDATE. If no rows was affected, it will fall back to emitting an INSERT.

like image 28
chribsen Avatar answered Sep 17 '22 22:09

chribsen