Noob question, but I cannot find answer anywhere. I want to pre-populate my database with some values, which refer to each other via foreign keys. But I see no way to do that without explicitly using IDs, which are supposed to be auto generated and therefore invisible to me. Approach which I hoped would work:
create table A
(
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
str TEXT NOT NULL
);
insert into A(str)
values ('a'),
('b'),
('c');
create table B
(
id INT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
a INT REFERENCES A
);
with found as (select id from A where str = 'b')
insert
into B(a)
values (found),
(found),
(found);
2
Answers
It seems that only some expressions are allowed as VALUES. I cannot use the table name nor (contrary to the documentation) column reference
found.id
. But I can use a scalar subquery(select * from found)
or in simpler form(table found)
:which is ugly, but works.
Add a
returning
clause to yourinsert into A
, wrap that in awith
common table expression or a subquery, then select from that when youinsert into B
. Demo at db<>fiddle:Remember that in PostgreSQL, unless you double-quote your identifiers, they are folded to lowercase, so
A
is justa
, unless you create it as"A"
.