Home > Database > Mysql Tutorial > How Can PostgreSQL's CTEs Efficiently Handle Multiple INSERTs with RETURNING for Multi-Table Updates?

How Can PostgreSQL's CTEs Efficiently Handle Multiple INSERTs with RETURNING for Multi-Table Updates?

Mary-Kate Olsen
Release: 2025-01-02 14:05:40
Original
940 people have browsed it

How Can PostgreSQL's CTEs Efficiently Handle Multiple INSERTs with RETURNING for Multi-Table Updates?

Multiple INSERT...RETURNING for Multi-Table Updates in PostgreSQL

Inserting data into multiple child tables while referencing newly inserted data from a parent table can be a challenging task. In this context, PostgreSQL provides a powerful solution using data-modifying common table expressions (CTEs).

Initially, we can retrieve the user_id of a newly inserted row in a parent table using the RETURNING clause:

INSERT INTO table1 (default,'johnee','john','smith',default) RETURNING userid;
Copy after login

To perform the multiple INSERTs, we can utilize data-modifying CTEs as follows:

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;
Copy after login

In this code, the ins1 CTE performs the INSERT into table1 and returns the user_id. The ins2 CTE then uses the user_id from ins1 to insert data into table2. Finally, the third INSERT uses the user_id from ins1 to insert data into table3, optionally returning the resulting user_id.

By using data-modifying CTEs, we can efficiently chain multiple INSERTs and ensure that the newly inserted data in child tables maintains the necessary relationships with the parent table.

The above is the detailed content of How Can PostgreSQL's CTEs Efficiently Handle Multiple INSERTs with RETURNING for Multi-Table Updates?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template