Skip to content

Instantly share code, notes, and snippets.

@nosamanuel
Created April 24, 2014 16:26
Show Gist options
  • Select an option

  • Save nosamanuel/11260660 to your computer and use it in GitHub Desktop.

Select an option

Save nosamanuel/11260660 to your computer and use it in GitHub Desktop.
Simple upsert in Postgres using a writeable CTE
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