Thread: [GENERAL] upsert and update filtering
Hi create table dimc1 ( col1 integer not null, col2 char(10), primary key (col1) ); create table dimc2 ( col1 integer not null, col2 char(10), primary key (col1) ); testdb=# select * from dimc1 order by 1; col1 | col2 ------+------------ 111 | foo111 112 | foo112 (2 rows) testdb=# select * from dimc2 order by 1; col1 | col2 ------+------------ 111 | foo111 112 | foo122 211 | foo211 In general it is my understanding it gows like this insert into dimc1 select * from dimc2 on conflict (col1) do update SET col2 = EXCLUDED.col2 ; insert into dimc1 select * from dimc2 on conflict (col1) do update SET col2 = EXCLUDED.col2 returning * ; So far so good But what if in the conflict situation I want to performa the update ONLY if the record is different. The update seems tohappen no matter what In other words is there anyway I can filter the update to happen (based on the sample date) only for 112 since col2 is different? testdb=# select * from dimc1 order by 1; col1 | col2 ------+------------ 112 | foo112 testdb=# select * from dimc2 order by 1; col1 | col2 ------+------------ 112 | foo122 Thanks Armand
armand pirvu <armand.pirvu@gmail.com> wrote: >But what if in the conflict situation I want to performa the update ONLY if the record is different. The update seems tohappen no matter what >In other words is there anyway I can filter the update to happen (based on the sample date) only for 112 since col2 is different? That's quite possible. An ON CONFLICT's UPDATE accepts a WHERE clause, which can reference both existing and excluded tuples. That WHERE clause can back out of the UPDATE based on whatever criteria you like. -- Peter Geoghegan
aaaa That's because the access on this case is done to the existing row using the table's name / alias , and to the rows thatwe attempt to insert using the excluded Thank you Peter Armand > On Jul 31, 2017, at 4:31 PM, Peter Geoghegan <pg@bowt.ie> wrote: > > armand pirvu <armand.pirvu@gmail.com> wrote: >> But what if in the conflict situation I want to performa the update ONLY if the record is different. The update seemsto happen no matter what >> In other words is there anyway I can filter the update to happen (based on the sample date) only for 112 since col2 isdifferent ? > > That's quite possible. An ON CONFLICT's UPDATE accepts a WHERE clause, > which can reference both existing and excluded tuples. That WHERE clause > can back out of the UPDATE based on whatever criteria you like. > > -- > Peter Geoghegan