Skip to content
Advertisement

Postgres Function to insert multiple records in two tables

I have (very simplified sample) tables as above, into which I want to insert details of an order and order details in one action.

I am familiar with transactions, and could insert data with an SQL command like the below:

However, ideally I’d like to have a query like the above a function if possible, rather than being stored within my application.

Could anyone point me in the right direction for supplying multiple records to a postgres function? Alternatively, if what I am looking to do is considered bad practice, please let me know what other route I should follow.

Thanks in advance.

Advertisement

Answer

You can use an array of tuples to pass multiple rows to the function. You need a custom type:

Use array of this type for an argument of the function:

Usage:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement