patternsqlMinor
INSERT INTO using the RETURNING values from another INSERT
Viewed 0 times
theinsertintoreturningusinganothervaluesfrom
Problem
I'd like to do something like this:
And then I would expect a new record in table2 with
INSERT INTO table2(name)
INSERT INTO table1(name, address) VALUES ('me', 'home')
RETURNING name;And then I would expect a new record in table2 with
'me' in name. This would work fine with a SELECT returning the values, but I'm having trouble with the nested insert.Solution
Use a data modifying CTE:
with t1 (name) as (
INSERT INTO table1 (name, address) VALUES ('me', 'home')
returning name
)
insert into table2 (name)
select name
from t1;Code Snippets
with t1 (name) as (
INSERT INTO table1 (name, address) VALUES ('me', 'home')
returning name
)
insert into table2 (name)
select name
from t1;Context
StackExchange Database Administrators Q#132541, answer score: 5
Revisions (0)
No revisions yet.