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