Skip to content
Advertisement

PostgreSQL – Insert data into multiple tables simultaneously

I am having a data insertion problem in tables linked by foreign key. I have read in some places that there is a “with” command that helps in these situations, but I do not quite understand how it is used.

I would like to put together four tables that will be used to make a record, however, that all the data were inserted at once, in a single query, and that they were associated with the last table, to facilitate future consultations. Here is the code for creating the tables:

Advertisement

Answer

The idea is to write WITH clauses that contain INSERT ... RETRUNING to return the generated keys. Then these “views for a single query” can be used to insert those keys into the referencing tables.

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