Created
March 24, 2015 13:11
-
-
Save kudryashov-sv/91b1ac5f9f62908bb309 to your computer and use it in GitHub Desktop.
CTE upsert for postgresql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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