json

jsonb_set

Postgres function that returns a copy of target with the value at path replaced by new_value. Creates the key if create_missing (default true); paths use text arrays like '{users,0,name}'.

jsonb_set(target, path text[], new_value jsonb [, create_missing])

Parameters / Modifiers

Parameter Purpose
create_missing If false, do nothing when the path does not already exist
jsonb_insert Sibling function that inserts without overwriting existing keys
|| operator Shallow merge of two jsonb values (top-level only)

Examples

SELECT jsonb_set('{"a":1}'::jsonb, '{a}', '2');

Returns {"a": 2}

UPDATE users SET data = jsonb_set(data, '{prefs,theme}', '"dark"');

Nested key update, quotes required because the new value is JSON

SELECT jsonb_set('{}'::jsonb, '{a,b}', '1', true);

Returns {"a": {"b": 1}} — auto-creates the parent object

SELECT jsonb_set('[10,20,30]'::jsonb, '{1}', '99');

Array element by index — returns [10, 99, 30]

Dialect notes / Gotcha

Postgres-only, and only on jsonb (not json). The new_value must itself be jsonb — string literals need extra quotes ('"dark"'::jsonb).

Related functions

← All SQL functions · SQL cheat sheet · Window functions · PostgreSQL cheat sheet