With the table like this:
CREATE TABLE test_1 ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY);CREATE TABLE test_2 ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY);CREATE TABLE test_refs ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, id_1 bigint NOT NULL REFERENCES test_1, id_2 bigint NOT NULL REFERENCES test_2);
And the insert query like this:
WITH new_test_1_rows AS ( INSERT INTO test_1 DEFAULT VALUES RETURNING *), new_test_2_rows AS ( INSERT INTO test_2 DEFAULT VALUES RETURNING *), test_row_pairs AS ( INSERT INTO test_refs ( id_1, id_2 ) VALUES ( (SELECT id FROM new_test_1_rows), (SELECT id FROM new_test_1_rows) ) RETURNING *)SELECT *FROM test_row_pairs
Basically what it does:
- inserts a row into
test_1
- inserts a row into
test_2
- inserts their IDs pair into
test_refs
The problem is I would like to rewrite the query into a multi-insert query, i.e. for the n
rows inserted into test_1
insert the n
rows into test_2
and then create the n
rows in test_refs
for the inserted values. For that I need to know the row index within the CTE, so it could be used as a join key. Is it something you can do within the RETURNING
clause?