Home >Database >Mysql Tutorial >How Can I Efficiently Chain Multiple INSERT Statements with RETURNING in PostgreSQL?
Chaining Multiple INSERTs with RETURNING in PostgreSQL
When working with hierarchical database structures, it's often necessary to insert data into multiple tables with dependencies. In PostgreSQL, a combination of data-modifying CTEs and the RETURNING clause provides an efficient solution.
To insert a new row into the parent table table1 and populate the relevant rows in the child tables table2 and table3, follow these steps:
WITH ins1 AS ( INSERT INTO table1 (username, name, surname) VALUES ('johnee','john','smith') RETURNING user_id ) , ins2 AS ( INSERT INTO table2 (user_id, password) SELECT ins1.user_id, 'secret' FROM ins1 ) INSERT INTO table3 (user_id, adress, city, phone) SELECT ins1.user_id, ... FROM ins1 RETURNING user_id;
Breaking Down the CTE Chain:
Benefits of Using Data-Modifying CTEs:
The above is the detailed content of How Can I Efficiently Chain Multiple INSERT Statements with RETURNING in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!