Для одной записи - все просто:
Для множественного обновления сложнее. Вот что придумалось:
Что то как то немного брейнфак =) Может, есть способ проще?
Код:
# create table t (id int, s varchar(255), primary key(id));
# insert into t values (1, 'a'), (2, 'b');
INSERT 0 2
# with updated as (update t set s='bb' where id=2 returning id)
insert into t select 2, 'bb' where not exists(select 1 from updated);
INSERT 0 0
# with updated as (update t set s='cc' where id=3 returning id)
insert into t select 3, 'cc' where not exists(select 1 from updated);
INSERT 0 1
# select * from t;
id | s
----+----
1 | a
2 | bb
3 | cc
(3 rows)
Код:
with
data as
(select 1 as id, 'aaa' as s union select 2, 'bbb'),
updated as
(update t set s = data.s from data where t.id = data.id returning t.id)
insert into t
select
id, s
from
data
where
data.id not in (select id from updated);