Skip to content
Advertisement

Update a field in a JSON column in PostgreSQL

I have a work_item table that has the following schema

and a document_type table with the following schema:

The data column is a json column that has a Type field. This is a sample column data:

I need to update data columns whose data_type column value is DocumentModel and Type field values matches a value in the name column of the document_type table to a json object containing the document_type id and the document_type name. Something like this {"id": "<doc_type_id>", name: "<doc_type_name>"}.

I tried to do this by executing this query:

The above script runs without an error. However, what it does is something unwanted, it changes the data and data_type columns to null instead of updating the data column.

What is the issue with my script? Or can you suggest a better alternative to do a the desired update?

Advertisement

Answer

The problem arises when the document type is missing from the document_type table. Then jsonb_set() returns null (as the subquery does not give any results). A safer solution is to use the from clause in update:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement