I have been shown a great way to bulkinsert with this example:
WITH p AS (
INSERT INTO parent_table (column_1)
SELECT $1
RETURNING id)
INSERT INTO child_table (parent_table_id, column_a)
SELECT p.id, a
FROM p, unnest($2::text[]) AS a
However, I need to insert multiple rows from multiple arrays, so I tried this syntax:
WITH p AS (
INSERT INTO parent_table (column_1)
SELECT $1
RETURNING id)
INSERT INTO child_table (parent_table_id, column_a, column_b)
SELECT p.id, a, b
FROM p, unnest($2::text[]) AS a, unnest($3::bigint[]) AS b
I have a primary key on parent_table_id
and column_a
, and when I try to execute this query, Postgres complains of a duplicate key violation.
How should the arrays be unwrapped so that they form individual rows?
In other words, if $2
and $3
both have two entries, how can the first entry of $2
only be inserted with the first entry of $3
and the same for the respective second entries?
If this is not possible, can I construct a multidimensional array? If so, how should it be passed with multiple array types, and what is the multidimensional array syntax?