Answer the question
In order to leave comments, you need to log in
What upsert implementations for Postgresql 9.3 do you recommend to use?
Challenge:
replicate mysql "ON DUPLICATE KEY UPDATE" behavior for postgresql 9.3 in the least perverse way
Answer the question
In order to leave comments, you need to log in
Prior to version 9.5, you can use the following solution:
WITH upsert AS (
UPDATE tbl SET foo = 42 RETURNING *
)
INSERT INTO tbl(foo) VALUES(42) WHERE tbl.id NOT IN (SELECT id FROM upsert);
with s as (
some select with id column
), u as (
update target_table_with_id_column as t set
column = s.corresponding_column
...
from s where t.id = s.id
returning t.id, 'update'::text as command
), i as (
insert into target_table_with_id_column select s.* from s left join u using (id) where u.id is null returning id, 'insert'::text as command
) select command, count(id) from i group by 1 union select command, count(id) from u group by 1
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question