I am using SQL after a long time and I have following:
I have existing table1
with columns id
, name
and a lot of other columns, it already contains rows.
I created empty table2
which only has columns id
and name
.
I created empty table3
which only has reference columns table1_id
and table2_id
.
Now I want to:
- take all the values from column
name
intable1
(can be NULL, discard them in that case), - insert them as new rows into
table2
, - insert
id
s of the correspondingtable1
andtable2
rows intotable3
, - remove the column
name
fromtable1
.
=> probablyALTER TABLE table1 DROP COLUMN name;
, but I guess there may be a neater way to cut the result from step 1, transform it and paste as rows in step 2.
EDIT: I came up with something like (not tested yet):
SELECT table1.id, table1.name INTO results FROM table1;
FOR result1 IN
results
LOOP
WITH result2 AS (
INSERT INTO table2 (name) VALUES (result1.name) RETURNING id
)
INSERT INTO table3 (table2_id, table1_id) VALUES (result2.id, result1.id);
END LOOP;
ALTER TABLE table1 DROP COLUMN name;
EDIT:
I forgot to tell that if the name
already existed in table2
, I don't want to add it again (should be unique in table2), but I add the relation between the id
from table1
and from the inserted/existing id
from table2
into the table3
.
EDIT: I found we have source scripts for creating the database and I changed it there. Now I don't know how to get rid of this open question :(