How to insert multiple rows into table B, and update table A's null foreign keys with the new IDs?

Viewed 55

I've found a million things sounding kind of similar on StackOverflow, but not my case exactly. I'll simplify as much as possible:

I have two tables as follows:

CREATE TABLE B (id uuid PRIMARY KEY);
CREATE TABLE A (id uuid PRIMARY KEY, b_id uuid REFERENCES b);

There are some NULL values in A.b_id. I am trying to create a migration that does the following:

For every row in A with no b_id, create a new row in B, and assign its id to A.b_id.

How can I accomplish this in one query?

1 Answers
Related