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.
Code
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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What relations does the SQL touch?
- The references are `user_prefs`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.