I have a postgresql table that has a column that contains the jsonb data for the row. Not all of the data was extracted from the jsonb to create the table but we wanted to store it in case we need to extract more data.
We now would like to pull one more field from the jsonb in the row and create a new column to store the value. The examples I have seen do not seem to address this specifically thus makes me want to double check my process and to see if there is an easier way to do this in PostgreSQL.
My insert statement looks like this:
insert into companyTable (company_id)
select company_object ->>'CompanyId'
from companyTable
This should then extract the value from the jsonb company_obejct and insert into the column company_id for each row in the table. Does this look correct and is their an easier way to accomplish this task?
UPDATE:
Given @Łukasz Kamiński statement it appears that I want to UPDATE not insert as INSERT adds new row and I just want to update the row where the new column has been added. With that I believe this is the code I should be using.
update companyTable
set (company_id) =
(select company_object ->>'CompanyId'
from company.company)
Also, because I am not understanding fully the context of UPDATE should this be placed in a loop so it updates each row with that rows jsonb object?
for example (before update):
id | col1 | company_object | company_id
---|------|--------------------------|------------
1 | a |{'b':1, 'company_id': 3} | NULL
2 | a |{'b':2, 'company_id': 4} | NULL
3 | a |{'b':3, 'company_id': 5} | NULL
(after update)
id | col1 | company_object | company_id
---|------|--------------------------|------------
1 | a |{'b':1, 'company_id': 3} | 3
2 | a |{'b':2, 'company_id': 4} | 4
3 | a |{'b':3, 'company_id': 5} | 5
companyTable?company_idof the existing rows.