Created
April 24, 2014 16:26
-
-
Save nosamanuel/11260660 to your computer and use it in GitHub Desktop.
Simple upsert in Postgres using a writeable CTE
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
| create table foo (id serial primary key, data json); | |
| with updated_foo as ( | |
| update foo set data = '"bar"' where id = 1 | |
| returning id | |
| ) | |
| insert into foo (id, data) | |
| select 1, '"foo"' | |
| where not exists(select id from updated_foo); | |
| -- data is inserted with value "foo" | |
| with updated_foo as ( | |
| update foo set data = '"bar"' where id = 1 | |
| returning id | |
| ) | |
| insert into foo (id, data) | |
| select 1, '"foo"' | |
| where not exists(select id from updated_foo); | |
| -- data is updated with value "bar" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment