I have the following tables in a Postgres database (trivialized example):
Table A
person_id | UNIQUE SERIAL integer
first_name | text
last_name | text
full_name_id | integer[]
Table B
full_name_id | UNIQUE SERIAL integer
full_name | text
For each row of Table A, I would like to insert a new row into Table B with full_name = first_name || last_name, and update the new full_name_id in the corresponding row in Table A.
Is it possible to write a single query that does this?
This is what I have so far (again, trivialized):
WITH a AS (
SELECT first_name, last_name
FROM table_a
)
INSERT
INTO table_b(full_name)
SELECT first_name || last_name AS full_name
FROM a
RETURNING full_name_id;
In my real-world scenario, a similar query successfully inserts correct rows in Table B. However, I'm not sure what to do next, to update full_name_id in Table A.
Note: the full_name_id column in Table A is an array to better reflect my real-world scenario (one row in Table A can reference multiple rows in Table B). To the best of my knowledge, this means I can't use foreign keys.