Context
Schema setup
create table users( id serial primary key );
Query 1
with t1 as (
insert into users default values
returning id
), t2 as (
insert into users default values
returning id
)
select id from t1;
Expectations
1
Result
1
Query 2
with t1 as (
insert into users default values
returning id
), t2 as (
insert into users default values
returning id
)
select id from t2;
Expectations
2
Result
1
Query 3
with t1 as (
insert into users default values
returning id
), t2 as (
insert into users default values
returning id
)
select id from t1
union all
select id from t2;
Expectations (taking in account results of Query 2)
1
1
Result
1
2
Question
What's wrong with my expectations and how to get the expected value from Query 2?
select max( id ) from ( select Id from t1 union all ... from tN )? – bessgeor Dec 19 '17 at 09:31lastval()) – Dec 19 '17 at 09:33t1insidet2. Something like:with t1 as ( insert into users default values returning id ), t2 as ( insert into users (select nextval('users_id_seq') where exists (table t1)) returning id ) select id from t2;– ypercubeᵀᴹ Dec 19 '17 at 10:06To add some context, I am writing simple CR-only sql generator, so I have to use pretty generic statements not to overcomplicate query generation.
– bessgeor Dec 19 '17 at 10:18