I would like to use a modifying CTE to insert some values. The insert statement inserts data from a select statement. I use the returning keyword to return the values inserted (including auto-incrementing columns). However, I also want that CTE to return other columns. How can I do this?
An example follows:
drop table if exists customers;
CREATE TABLE customers (
customer_id serial PRIMARY KEY,
name VARCHAR UNIQUE,
email VARCHAR NOT NULL,
active bool NOT NULL DEFAULT TRUE
);
INSERT INTO customers (NAME, email)
VALUES
('IBM', 'contact@ibm.com'),
(
'Microsoft',
'contact@microsoft.com'
),
(
'Intel',
'contact@intel.com'
);
drop table if exists customers2;
CREATE TABLE customers2 (
customer_id serial PRIMARY KEY,
name VARCHAR UNIQUE,
email VARCHAR NOT NULL
);
with x as (
INSERT INTO customers2 (NAME, email)
select name, email from customers
returning customer_id, name, email, active
)
select * from x
;
I would like the last statement to return columns customer_id, name, email, active. But I get an error:
Error: ERROR: column "active" does not exist
Position: 123
SQLState: 42703
ErrorCode: 0
Error occurred in:
with x as (
INSERT INTO customers2 (NAME, email)
select name, email from customers
returning customer_id, name, email, active
)
select * from x
Best Answer
According Postgres Docs about 6.4. Returning Data From Modified Rows you can't.
Quoted from docs:
Unless this data is updated by a trigger:
You can check it by using
RETURNING *
db<>fiddle here
You could get it by using a nested CTE:
db<>fiddle here