Currently I have two postgresql tables table1 and table2, shown below, primary key is id
.
table1:
id | name
----------
1 | Bob
3 | Steven
table2:
id | name
----------
2 | John
3 | Jack
I would like to combine these two tables by inserting table2 to table1, and table1 should look like below after the operation. Essentially, it can maintain the same primary key if there is no conflict, but when it has conflict, it will generate a new id for the incoming data from table2, and insert that as a new role in table1. In this example, Jack
from table2 will have a new id
of 4 (max id from table1 + 1).
id | name
----------
1 | Bob
2 | John
3 | Steven
4 | Jack
Below is my current approach. Which updates the id in conflicted row in table1.
INSERT INTO table1 (id, name)
SELECT id, name
FROM table2
ON CONFLICT(id) DO UPDATE SET id=nextval(pg_get_serial_sequence('table1', 'id'));
I need help figuring out how to insert into a new role with a new id.