Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT INTO ... RETURNING multiple columns (PostgreSQL)

Tags:

sql

postgresql

I've searched around for an answer and it seems definitive but I figured I would double check with the Stack Overflow community:
Here's what I'm trying to do:

INSERT INTO my_table VALUES (a, b, c)
RETURNING (SELECT x, y, z FROM x_table, y_table, z_table
WHERE xid = a AND yid = b AND zid = c)

I get an error telling me I can't return more than one column.
It works if I tell it SELECT x FROM x_table WHERE xid = a.

Is this at all possible in a single query as opposed to creating a seperate SELECT query?

I'm using PostgreSQL 8.3.

like image 893
Itamar Bitton Avatar asked Dec 11 '13 00:12

Itamar Bitton


People also ask

How do I run multiple inserts in PostgreSQL?

PostgreSQL INSERT Multiple Rows First, specify the name of the table that you want to insert data after the INSERT INTO keywords. Second, list the required columns or all columns of the table in parentheses that follow the table name. Third, supply a comma-separated list of rows after the VALUES keyword.

How can I insert multiple records in a SQL table using a single insert statement?

INSERT-SELECT-UNION query to insert multiple records Thus, we can use INSERT-SELECT-UNION query to insert data into multiple rows of the table. The SQL UNION query helps to select all the data that has been enclosed by the SELECT query through the INSERT statement.

What does insert query return in Postgres?

PostgreSQL used the OID internally as a primary key for its system tables. Typically, the INSERT statement returns OID with value 0. The count is the number of rows that the INSERT statement inserted successfully.


2 Answers

Try this.

with aaa as (
    INSERT INTO my_table VALUES(a, b, c)
    RETURNING a, b, c)
SELECT x, y, z FROM x_table, y_table, z_table
WHERE xid = (select a from aaa)
  AND yid = (select b from aaa)
  AND zid = (select c from aaa);

In 9.3 similar query works.

like image 151
corvinusz Avatar answered Sep 25 '22 04:09

corvinusz


@corvinusz answer was wrong for 8.3 but gave me a great idea that worked so thanks!

INSERT INTO my_table VALUES (a, b, c)
RETURNING (SELECT x FROM x_table WHERE xid = a),
  (SELECT y FROM y_table WHERE yid = b),
  (SELECT z FROM z_table WHERE zid = c)

I have no idea why the way it's stated in the question is invalid but at least this works.

like image 36
Itamar Bitton Avatar answered Sep 26 '22 04:09

Itamar Bitton