SoFunction
Updated on 2025-04-08

Postgresql updates through query

I won't say much nonsense, let's just look at the examples~

UPDATE tb1
SET c1=b.c1 ,
c2=b.c2
FROM b
WHERE tb1.c3 = b.c3 AND tb1.c4 = b.c4

Supplement: Postgresql database is updated if it exists, and insert if it does not exist.

Format:

insert into ...... on conflict(column_name) do ......

example:

uxdb=# create table tbl_c (id int unique, name varchar(2));
CREATE TABLE
uxdb=# insert into tbl_c values (1, 'a');
INSERT 0 1
uxdb=# table tbl_c;
 id | name 
----+------
 1 | a
(1 row)
uxdb=# insert into tbl_c values (1, 'a');
ERROR: duplicate key value violates unique constraint "tbl_c_id_key"
DETAIL: Key (id)=(1) already exists.
uxdb=# insert into tbl_c values (1, 'a') on conflict(id) do update set name='b';
INSERT 0 1
uxdb=# table tbl_c;
 id | name 
----+------
 1 | b
(1 row)
 
uxdb=# 

Note: The column_name in conflict(column_name) must be a primary key or unique

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.