jsonb_set_lax Handles Missing Paths
Update nested JSON documents with jsonb_set_lax, whose null_value_treatment decides whether SQL NULL becomes JSON null, a deleted key, or an error.
Code
-- jsonb_set 的规则:路径中任一父级缺失时原样返回,更新静默无效
SELECT jsonb_set('{"a":1}'::jsonb, '{b,c}', '2') AS parent_missing_noop;
-- jsonb_set_lax 在 replacement 非 NULL 时行为与 jsonb_set 相同:
-- create_if_missing 只管最后一级,父级缺失仍然原样返回
SELECT jsonb_set_lax('{"a":1}'::jsonb, '{b,c}', '2', true) AS still_noop,
jsonb_set_lax('{"a":1}'::jsonb, '{b}', '2', true) AS creates_b,
jsonb_set_lax('{"a":1}'::jsonb, '{b}', '2', false) AS no_create_noop;
-- 新值传 NULL:默认 null_value_treatment 是 use_json_null,写成 JSON null
SELECT jsonb_set_lax('{"a":1}'::jsonb, '{a}', NULL) AS json_null_written;
-- 想删键或保持原样时显式指定:delete_key / return_target
SELECT jsonb_set_lax('{"a":1}'::jsonb, '{a}', NULL, true, 'delete_key') AS key_removed,
jsonb_set_lax('{"a":1}'::jsonb, '{a}', NULL, true, 'return_target') AS unchanged;How it works
Both functions in the file are called on literals, so no table is touched: each statement returns a distinct jsonb document in one column.
The plain jsonb_set establishes the baseline rule — a path whose parent is missing leaves the document exactly as it was, with no error raised.
What jsonb_set_lax adds
jsonb_set_lax keeps that behaviour for non-NULL replacements and adds a policy for the NULL case. The fourth argument decides whether a missing final key is created; the fifth picks what a NULL replacement means.
Key statements
SELECT jsonb_set_lax('{"a":1}'::jsonb, '{b}', '2', true) AS creates_b;
SELECT jsonb_set_lax('{"a":1}'::jsonb, '{a}', NULL, true, 'delete_key') AS key_removed;
Interactive Tools for This Topic
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.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.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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.