How to insert a single row in the parent table and then multiple rows in the child table in single SQL in PostgreSQL?
PostgreSQL has such an extended interpretation of the VALUES
clause that it may be used as a subquery by itself.
So you may express your query in this form:
WITH new_invoice AS (
INSERT INTO ...
RETURNING id
),
v(a,b,c,d) AS (values
($27,$28,$29,$30),
($31,$32,$33,$34),
...
)
INSERT INTO invoiceItems (invoice_id, name, qty, price, description)
SELECT new_invoice.id, a,b,c,d FROM v, new_invoice;
That assumes you want to insert the cartesian product of new_invoice
and the values, which mostly makes sense if new_invoice
is actually a single-row value.