How to use INSERT INTO RETURNING value as a subquery?

Viewed 17

I am trying to use the return value of a subquery in another query, but there is an error when using INSERT INTO as a subquery

SELECT * FROM (INSERT INTO items (name) VALUES ("test") RETURNING id);

The error message says:

ERROR:  syntax error at or near "INTO"

How to fix this?

1 Answers

you could use a CTE for that

But don't use in Postgres doubole quotes for text, it thinks that is a column, use single quotes instead

CREATE TABLe items(id SERIAL, name varchar(29))
CREATE TABLE
WITH INSERT_CTE as (INSERT INTO items (name) VALUES ('test') RETURNING id)
SELECT id FROM INSERT_CTE;

id
1
SELECT 1

fiddle

Related