Skip to content

Instantly share code, notes, and snippets.

@kudryashov-sv
Created March 24, 2015 13:11
Show Gist options
  • Save kudryashov-sv/91b1ac5f9f62908bb309 to your computer and use it in GitHub Desktop.
Save kudryashov-sv/91b1ac5f9f62908bb309 to your computer and use it in GitHub Desktop.
CTE upsert for postgresql
db=> create table what(id serial primary key, v text);
CREATE TABLE
db=> with upsert as (update what set v='updated value' where id=42 returning *) insert into what(id, v) select 42, 'inserted value' where not exists (select * from upsert);
INSERT 0 1
db=> select * from what;
id | v
----+----------------
42 | inserted value
(1 row)
db=> with upsert as (update what set v='updated value' where id=42 returning *) insert into what(id, v) select 42, 'inserted value' where not exists (select * from upsert);
INSERT 0 0
db=> select * from what;
id | v
----+---------------
42 | updated value
(1 row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment