Skip to content

Instantly share code, notes, and snippets.

@yancya
Last active May 23, 2018 10:02
Show Gist options
  • Save yancya/d6b94746696f95b61814917620c13fa7 to your computer and use it in GitHub Desktop.
Save yancya/d6b94746696f95b61814917620c13fa7 to your computer and use it in GitHub Desktop.
create temp table hoge(id integer, name text);
with hoge_candidate(id, name) AS (values(1, 'hoge'))
, inserted_hoge AS (
insert into hoge
select hoge_candidate.*
from hoge right outer join hoge_candidate using(id)
where hoge.id is null returning *)
select * from inserted_hoge
union
select hoge.* from hoge join hoge_candidate using(id);
-- id | name
-- ----+------
-- 1 | hoge
-- (1 row)
with hoge_candidate(id, name) AS (values(1, 'piyo'))
, inserted_hoge AS (
insert into hoge
select hoge_candidate.*
from hoge right outer join hoge_candidate using(id)
where hoge.id is null returning *)
select * from inserted_hoge
union
select hoge.* from hoge join hoge_candidate using(id);
-- id | name
-- ----+------
-- 1 | hoge
-- (1 row)
with hoge_candidate(id, name) AS (values(2, 'fuga'))
, inserted_hoge AS (
insert into hoge
select hoge_candidate.*
from hoge right outer join hoge_candidate using(id)
where hoge.id is null returning *)
select * from inserted_hoge
union
select hoge.* from hoge join hoge_candidate using(id);
-- id | name
-- ----+------
-- 2 | fuga
-- (1 row)
select * from hoge;
-- id | name
-- ----+------
-- 1 | hoge
-- 2 | fuga
-- (2 rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment