Reputation: 2497
I an postgres transaction I want to insert 1 record each to two tables say A & B, B has a foreign key to the record inserted to A in the same transaction.
How do I refer the inserted record here so that I can insert on table B
Upvotes: 0
Views: 864
Reputation:
You didn't specify the actual table structure, so I have to make things up, but a data modifying CTE can be used to do that in one statement
with new_a_row as (
insert into a (col1, col2, col3)
values ('one', 'two', 42)
returning id --<<< this is the generated primary key of the table A
)
insert into b (b_col_one, b_col_two, fk_col_to_a)
select 100, 'something', id
from new_a_row;
Alternatively use lastval()
and do this in two statements
begin;
insert into a (col1, col2, col3)
values ('one', 'two', 42);
insert into b (b_col_one, b_col_two, fk_col_to_a)
values (100, 'something', lastval());
commit;
The first solution will work with any "generation strategy" not only identity
or serial
columns but also if you e.g. use gen_random_uuuid()
as a default value.
The second solution requires an identity
or the old serial
type column.
Upvotes: 2