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.
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.
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.
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.
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.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With