Sub topic 7
Updating documents with jsonb_set, || and -
This chapter covers how to change a jsonb value in place with jsonb_set, the || operator, and the - operator. It assumes you can write basic UPDATE statements, know JSON syntax, and have the orders table from the earlier chapters. You need PostgreSQL 12 or later.
The core idea: jsonb values are replaced, not edited
A jsonb value is immutable from SQL's point of view. There is no statement that changes one key inside a stored document. Each modifying function or operator takes a jsonb value and returns a new jsonb value. You then assign that result back to the column.
Two consequences follow:
- Every update writes a new version of the whole row, even if you changed one small key. PostgreSQL does not patch the document on disk.
- Calling a function such as
jsonb_setin aSELECTchanges nothing in the table. OnlyUPDATEstores the result.
The json type has none of these functions. They work only on jsonb. If a column is json, cast it first, for example details::jsonb.
The examples below use this starting data. Run it first if your table is empty.
CREATE TABLE IF NOT EXISTS orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL,
details jsonb NOT NULL
);
INSERT INTO orders (customer, details) VALUES
('Ada', '{"status": "paid", "total": 42.50, "items": [{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}], "shipping": {"city": "Oslo"}}'),
('Grace', '{"status": "pending", "total": 10.00, "items": [{"sku": "A1", "qty": 1}], "shipping": {"city": "Bergen"}}');Replacing a value with jsonb_set
The signature is:
jsonb_set(target jsonb, path text[], new_value jsonb, create_if_missing boolean DEFAULT true)targetis the document to change.pathis a text array that names the location, such as'{shipping,city}'.new_valuemust itself be validjsonb.create_if_missingcontrols whether a missing last key is added.
The new value must be JSON
The most common mistake is passing a plain string as new_value. A JSON string needs its own double quotes inside the SQL single quotes.
UPDATE orders
SET details = jsonb_set(details, '{status}', '"shipped"')
WHERE id = 1;The literal '"shipped"' is the JSON string "shipped". If you write 'shipped', PostgreSQL tries to parse it as JSON and fails with invalid input syntax for type json. Numbers, booleans, and null work without extra quotes, because '5', 'true' and 'null' are valid JSON. When the new value comes from a SQL value, build it with to_jsonb:
UPDATE orders
SET details = jsonb_set(details, '{shipping,city}', to_jsonb('Stavanger'::text))
WHERE id = 2;Paths into nested objects and arrays
The path lists object keys and array positions from the top. For arrays, the position is a zero-based integer written as text. A negative integer counts from the end.
-- Change the quantity of the first item in order 1
UPDATE orders
SET details = jsonb_set(details, '{items,0,qty}', '3')
WHERE id = 1;
-- Change the quantity of the last item in order 1
UPDATE orders
SET details = jsonb_set(details, '{items,-1,qty}', '5')
WHERE id = 1;You cannot say "every array element where sku is B7" in a path. A path points to one location. To change elements by condition, you rebuild the array, as shown later in this chapter.
Missing keys and create_if_missing
By default, jsonb_set adds the last path step if it does not exist, provided every earlier step exists.
UPDATE orders
SET details = jsonb_set(details, '{shipping,country}', '"NO"')
WHERE id = 1;This adds country inside shipping. If shipping itself were missing, nothing would change, because jsonb_set does not create more than one missing level. The document comes back unchanged and no error is raised. Use jsonb_set_lax or jsonb_set with several nested objects built by || when you need to create deep structures.
Pass false as the fourth argument when you want to update a key only if it already exists:
UPDATE orders
SET details = jsonb_set(details, '{discount}', '10', false)
WHERE id = 1;If discount is absent, the row is rewritten with the same content.
NULL arguments
If new_value is SQL NULL, jsonb_set returns SQL NULL for the whole document. With a NOT NULL column, the update then fails. This happens easily when the new value comes from an expression such as to_jsonb(some_column) and the source is NULL. Note that to_jsonb(NULL::text) returns SQL NULL, not JSON null. Use 'null'::jsonb to store a JSON null.
jsonb_set_lax (PostgreSQL 13 and later) handles this case with a fifth argument, null_value_treatment, which accepts raise_exception, use_json_null, delete_key, or return_target.
UPDATE orders
SET details = jsonb_set_lax(details, '{note}', NULL, true, 'delete_key')
WHERE id = 2;Merging and adding keys with ||
The || operator concatenates two jsonb values. For two objects, it merges keys, and the right operand wins when both sides have the same key.
SELECT '{"a": 1, "b": 2}'::jsonb || '{"b": 3, "c": 4}'::jsonb;
-- {"a": 1, "b": 3, "c": 4}This makes || the simplest way to set or add several top-level keys at once:
UPDATE orders
SET details = details || '{"tracking": "X1", "status": "shipped"}'::jsonb
WHERE id = 1;The merge is shallow
|| replaces whole values at the top level. It does not merge nested objects.
SELECT '{"shipping": {"city": "Oslo", "zip": "0150"}}'::jsonb
|| '{"shipping": {"city": "Bergen"}}'::jsonb;
-- {"shipping": {"city": "Bergen"}}The zip key is gone. To change one nested key without losing its siblings, use jsonb_set with a path, or merge the nested object yourself:
UPDATE orders
SET details = jsonb_set(details, '{shipping}', (details -> 'shipping') || '{"zip": "0150"}')
WHERE id = 1;Operands that are not both objects
If both operands are arrays, || joins them into one array. If one side is not an array, it is appended as a single element, which is a quick way to add to a list:
UPDATE orders
SET details = jsonb_set(details, '{items}', (details -> 'items') || '{"sku": "C3", "qty": 1}')
WHERE id = 1;Mixing an object and an array gives an array, which is rarely what you want when you meant to merge keys. Check that both sides are objects when you mean a key merge.
Removing data with -
The - operator removes data from the left operand. What it removes depends on the type of the right operand.
| Expression | Right operand | Effect |
|---|---|---|
| `details - 'tracking'` | text | Removes a top-level key (or a matching string element in an array) |
| `details - ARRAY['a','b']` | text[] | Removes several top-level keys |
| `details - 2` | integer | Removes the array element at that position, negative counts from the end |
| `details #- '{shipping,city}'` | text[] | Removes the value at a nested path |
Removing a key that does not exist is not an error. The document is returned unchanged.
UPDATE orders
SET details = (details || '{"tracking": "X1"}'::jsonb) - 'shipping'
WHERE id = 1;This single statement adds tracking and removes shipping. Because || and - have the same precedence and associate left to right, the parentheses here are for readability. The - with an integer applies to arrays only, so use it on details -> 'items' and not on the whole object:
UPDATE orders
SET details = jsonb_set(details, '{items}', (details -> 'items') - 0)
WHERE id = 1;To remove a nested key, use #-:
UPDATE orders
SET details = details #- '{shipping,city}'
WHERE id = 2;Changing array elements by condition
Paths cannot filter, so you expand the array, change what you need, and aggregate it again. The next statement doubles the quantity of every item with sku A1 in every order.
UPDATE orders o
SET details = jsonb_set(
o.details,
'{items}',
(
SELECT jsonb_agg(
CASE WHEN i ->> 'sku' = 'A1'
THEN jsonb_set(i, '{qty}', to_jsonb((i ->> 'qty')::int * 2))
ELSE i
END
ORDER BY n
)
FROM jsonb_array_elements(o.details -> 'items') WITH ORDINALITY AS t(i, n)
)
)
WHERE o.details -> 'items' @> '[{"sku": "A1"}]';WITH ORDINALITY numbers the elements, and ORDER BY n inside jsonb_agg keeps the original order. Without it, the order of the rebuilt array is not guaranteed. The WHERE clause limits the rewrite to rows that contain the sku, so other rows are not written needlessly. An order with an empty items array would make jsonb_agg return NULL, so guard against that case with COALESCE(..., '[]'::jsonb) if empty arrays occur in your data.
How an update flows
Costs and concurrency
- Whole-document rewrite. Changing one key writes the entire
jsonbvalue again. For large documents, this means more write volume, more table bloat, and more work for autovacuum. Values larger than about 2 kB are compressed and moved to TOAST storage, and each update writes a fresh copy of the whole document there. - Index maintenance. Updating a column that has a GIN index can prevent heap-only tuple (HOT) updates, so the index gets new entries on every change. An expression index on
details ->> 'status'also blocks HOT updates when the column is updated, because PostgreSQL checks the indexed column, not the key. - Lost updates. Two sessions that each read a document, change it in the application, and write the whole thing back will overwrite each other. Do the change inside the
UPDATEstatement, as in the examples above. The row lock held byUPDATEserializes concurrent changes, and the second statement re-evaluates against the latest committed version. - Constraints. A
CHECKconstraint such asdetails ? 'status'is evaluated on every update. Removing thestatuskey with-will fail if that constraint exists.
Common errors
| Symptom | Cause | Fix | Column | Column |
|---|---|---|---|---|
| `invalid input syntax for type json` | Passed `'shipped'` instead of `'"shipped"'` | Add JSON quotes or use `to_jsonb` | ||
| Whole column becomes `NULL` or a `NOT NULL` violation | `jsonb_set` got a SQL `NULL` new value | Use `'null'::jsonb`, `COALESCE`, or `jsonb_set_lax` | ||
| Update has no effect | A parent key in the path does not exist | Create the parent first, or merge with ` | ` | |
| Nested sibling keys disappear | Used ` | ` on a nested object | Use `jsonb_set` with a path | |
| `function jsonb_set(json, ...) does not exist` | Column is `json`, not `jsonb` | Cast with `::jsonb` or change the column type |
Exercise
Order 2 has the document {"status": "pending", "total": 10.00, "items": [{"sku": "A1", "qty": 1}], "shipping": {"city": "Bergen"}}. Write one UPDATE statement that sets status to "paid", adds a paid_at key with the value "2026-11-27", and changes the shipping city to "Trondheim" without removing any other shipping keys.
Show answer
UPDATE orders
SET details = jsonbset(
details || '{"status": "paid", "paidat": "2026-11-27"}'::jsonb,
'{shipping,city}',
'"Trondheim"'
)
WHERE id = 2;
The || operator sets the two top-level keys. Because || is shallow, the nested change uses jsonb_set with the path {shipping,city}, which keeps other keys inside shipping. The new city value needs JSON quotes.
Exercise
Why does SELECT jsonb_set('{"a": {"b": 1}}', '{x,y}', '2') return the original document unchanged, and how would you add the key x holding the object {"y": 2}?
Show answer
The path {x,y} needs x to exist, and jsonb_set creates only the last missing step, not intermediate levels, so nothing is added. Set the whole x value instead: SELECT jsonb_set('{"a": {"b": 1}}', '{x}', '{"y": 2}'), or use '{"a": {"b": 1}}'::jsonb || '{"x": {"y": 2}}'.