Migrate columns from table A to table B, and update A with a reference to B
0
votes
1
answer
179
views
I have a table A with some columns that need to be migrated to a new table B. But I also need to create a column in table A to reference the id's from the new columns in the table B. I've tried doing it this way but it's not working:
WITH cte AS (
INSERT INTO B (c1)
SELECT c1
FROM A
RETURNING id, A.id as "aId"
)
UPDATE A
SET bId = cte.id
FROM cte
INNER JOIN A on cte."aId" = A.id
;
This is the error message:
ERROR: missing FROM-clause entry for table A
LINE 5: RETURNING id, A.id as "aId"
^
SQL state: 42P01
Character: 168
I'm assuming this is because Postgres doesn't allow selecting from the table you are inserting the values and it only allows to return columns from the inserted row.
So how to accomplish this? I know it can probably work with a for
loop, but is there a cleaner way? I also tried updating table A directly from results of the insertion, but that didn't work as Postgres doesn't allow using the insert
statement in a subquery for updating.
Asked by Warix3
(1 rep)
Jun 26, 2023, 07:04 PM
Last activity: Jul 4, 2025, 11:04 PM
Last activity: Jul 4, 2025, 11:04 PM