Im trying to duplicate rows in my tables while keeping the same link between them.
Im using PGSQL. I will explain with examples.
Employer table:
ID | Name | ServiceProviderID | UpdatedAt |
---|---|---|---|
1 | Apple | 10 | 2024-04-24 15:35:24 |
2 | Microsoft | 11 | 2024-05-16 19:00:58 |
3 | Meta | 11 | 2024-05-08 17:03:08 |
I want to duplicate specific rows, based on its ServiceProviderID while changing only ServiceProviderID.
This is how I achieved it:
INSERT INTO employer (name, service_provider_id, updated_at)
SELECT name, 999, updated_at
FROM employer
WHERE service_provider_id = 11
RETURNING id;
It will result in both Microsoft and Meta rows being duplicated, because they have ServiceProviderID=11, but with ServiceProviderID changed to 999
However, on my Worker table, I cant figure out how to map them to the newly inserted Employer.
Worker table:
ID | Name | ServiceProviderID | EmployerID |
---|---|---|---|
1 | James Bond | 10 | 1 |
2 | Darth Vader | 11 | 2 |
3 | Marceline Abdr | 11 | 3 |
If I run below code:
INSERT INTO worker (name, service_provider_id, employer_id)
SELECT name, 999, employer_id
FROM worker
WHERE service_provider_id = 11
RETURNING id;
The employer_id will still be the same it was on the original worker row. But I need it to be the newly inserted employer_id it was associated to. How can I do that?
Gustavo Botti is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.