Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
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
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 $$;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question