V
V
Viktor2021-10-07 22:58:16
PostgreSQL
Viktor, 2021-10-07 22:58:16

Make two dependent INSERTs into different tables with one postgresql query?

Hello.
Prompt, it is necessary to make two insert in different tables, in one request. While the second insert depends on the results of the first. And at the same time, the data must definitely be inserted into both tables, and if for some reason the data was not inserted into one of the tables, then they should not be in the second.
If anything, I send the request from Node to postgresql.
I understand that a transaction is needed, but I still can't figure out how to use the insert result.
Request example.

INSERT INTO public.users(first_name, second_name, password) VALUES ($1, $2, $3) RETURNING id

INSERT INTO public.user_phone_number(user_id, phone_number) VALUES ($1, $2) RETURNING phone_number


In the $1 variable of the second request, use the id returned by the first request.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Victor, 2021-10-12
@VelkinVV

The issue can be resolved in two ways.
First

WITH user_data AS (INSERT INTO public.users(first_name, second_name, password) 
        VALUES ($1, $2, $3) RETURNING id, first_name, second_name), 
        user_phone AS (INSERT INTO public.user_phone_number(user_id, phone_number) 
        VALUES ((SELECT id FROM user_data), $4) RETURNING user_id, phone_number) 
        SELECT ud.id, ud.first_name, ud.second_name, up.phone_number 
        FROM user_data AS ud INNER JOIN user_phone AS up 
        ON up.user_id = ud.id

Second
DO $$
DECLARE tableId bigint;
BEGIN
INSERT INTO public.users(first_name, second_name, password) VALUES ($1, $2, $3) RETURNING id INTO tableId;
INSERT INTO public.user_phone_number(user_id, phone_number) VALUES (tableId, $4);
COMMIT;
END $$;

A
Andrey Tsvetkov, 2021-10-08
@yellow79

https://stackoverflow.com/questions/6560447/can-i-...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question