Handling JSON data is a common requirement in modern applications, and PostgreSQL’s jsonb
data type offers robust capabilities for storing and manipulating JSON data. Sometimes you may need to update nested fields within a jsonb
column. Here’s how you can efficiently update these nested JSONB fields using SQL.
Updating a nested JSONB field requires using the jsonb_set
function, which lets you modify existing JSON data. The jsonb_set
function takes three essential parameters:
UPDATE your_table
SET jsonb_column = jsonb_set(
jsonb_column,
'{parent_key, nested_key}',
'"new_value"',
true
)
WHERE condition;
Suppose you have a table contacts
with a jsonb
column named info
, and you want to update the city of a specific contact:
Current JSONB Value:
{
"name": "John Doe",
"address": {
"city": "Old City",
"state": "State"
}
}
SQL Update Statement:
UPDATE contacts
SET info = jsonb_set(
info::jsonb,
'{address, city}',
'"New City"',
true
)
WHERE info ->> 'name' = 'John Doe';
This query updates the city
field inside the address
object for the contact named “John Doe.”
By utilizing jsonb_set
, updating nested JSONB fields becomes a powerful tool in PostgreSQL, enabling seamless data manipulation within your database.
“`
This article is structured to provide clear information about updating nested JSONB fields in PostgreSQL and includes relevant links for further context and understanding.