Postgresql – INSERT INTO using the RETURNING values from another INSERT

insertpostgresql

I'd like to do something like this:

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.

Best Answer

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;