jsonb set Partial In Place Update

Update nested JSON paths with jsonb_set: provide the path array, the new value, and control whether missing keys get created.

SqlData Integrity

Code

snippet
CREATE TABLE user_prefs (
    user_id int PRIMARY KEY,
    prefs   jsonb NOT NULL
);

INSERT INTO user_prefs VALUES
    (1, '{"theme": "light", "prefs": {"lang": "zh"}}'),
    (2, '{}');

-- 修改嵌套键:路径数组逐层指路,值必须是 jsonb
UPDATE user_prefs
SET prefs = jsonb_set(prefs, '{prefs,lang}', '"en"')
WHERE user_id = 1;

-- 缺失路径默认补建(create_missing 默认 true):第 2 行长出新键
UPDATE user_prefs
SET prefs = jsonb_set(prefs, '{notifications,email}', 'true')
WHERE user_id = 2;

-- create_missing = false:路径不存在时整列保持原样
UPDATE user_prefs
SET prefs = jsonb_set(prefs, '{notifications,email}', 'false', false)
WHERE user_id = 1;

SELECT user_id, prefs FROM user_prefs ORDER BY user_id;
DROP TABLE user_prefs;

What the code does

Several statements share this file — SELECT / INSERT / UPDATE / CREATE, with user_prefs among the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Using it

Run it in the user_prefs database context.

Key statements

UPDATE user_prefs
SET prefs = jsonb_set(prefs, '{notifications,email}', 'false', false)
WHERE user_id = 1;
UPDATE user_prefs
SET prefs = jsonb_set(prefs, '{notifications,email}', 'true')
WHERE user_id = 2;
UPDATE user_prefs
SET prefs = jsonb_set(prefs, '{prefs,lang}', '"en"')
WHERE user_id = 1;

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
The references are `user_prefs`.