Sub topic 8
Changing documents with JSON_TRANSFORM and JSON_MERGEPATCH
This chapter assumes you can read SQL/JSON path expressions and know the orders table from earlier chapters. It has a JSON column named doc that holds order documents with customer, status, and an items array. You need Oracle Database 21c or later for the JSON type. JSON_TRANSFORM is available from 21c, and in 19c from release update 19.8 onward.
Why not rewrite the whole document
A JSON document is one column value, so the obvious way to change one field is to read the document, edit it in application code, and write all of it back. That approach has three problems:
- It moves the whole document across the network for a one-field change.
- It can overwrite another session's change to a different field.
- It forces every application to carry its own editing logic.
Oracle provides two SQL functions that apply changes inside the database:
JSON_TRANSFORMapplies a list of explicit operations.JSON_MERGEPATCHapplies a partial document that is merged into the target, following RFC 7396.
Both are functions. They return a modified document and do not change anything by themselves. To persist the result, you assign it in an UPDATE.
JSON_TRANSFORM
JSON_TRANSFORM(input, operation [, operation ...]) applies its operations from left to right. If any operation fails, the whole call fails and you get no partial result. Each operation names a path, which is a SQL/JSON path expression, and usually a new value.
This statement changes the status and removes a field in a single update:
UPDATE orders o
SET o.doc = JSON_TRANSFORM(o.doc,
SET '$.status' = 'SHIPPED',
REMOVE '$.customer.city')
WHERE JSON_VALUE(o.doc, '$.orderId' RETURNING NUMBER) = 1001;The common operations are listed below.
| Operation | What it does |
|---|---|
| `SET` | Sets a field. By default it creates the field if it is missing and replaces it if it exists. |
| `INSERT` | Adds a field or array element. Use it when you want to add a value without replacing an existing one. |
| `REPLACE` | Changes a value that must already be there. It does not create new fields. |
| `REMOVE` | Deletes a field or array element. |
| `APPEND` | Adds an element to the end of an array. |
| `PREPEND` | Adds an element to the start of an array. |
| `RENAME` | Changes a field name and keeps its value. |
| `KEEP` | Keeps only the listed paths and drops everything else. |
Handling missing and existing targets
Each operation has handlers that decide what happens when the path is missing or already exists. You can write them as ERROR ON MISSING, IGNORE ON MISSING, CREATE ON MISSING, REPLACE ON EXISTING, and IGNORE ON EXISTING. Which handlers an operation accepts, and its defaults, depend on the operation. State the handler explicitly when the behavior matters, as in this example:
SELECT JSON_TRANSFORM(
'{"orderId": 1001, "status": "NEW", "note": "gift"}',
SET '$.status' = 'PAID',
REMOVE '$.note' ERROR ON MISSING,
RENAME '$.status' = 'orderStatus'
) AS result
FROM dual;The result is shown below. Key order and spacing may differ on your system.
{"orderId":1001,"orderStatus":"PAID"}Note that the RENAME operation sees the output of the earlier SET, because operations run in sequence. If $.note were absent, ERROR ON MISSING would raise an error and the statement would return no result.
Working with arrays
Use APPEND to add an element to an array. The value you add is text by default, so mark it as JSON with FORMAT JSON. Without that marker, Oracle would add a JSON string that happens to contain braces.
UPDATE orders o
SET o.doc = JSON_TRANSFORM(
o.doc,
APPEND '$.items' = '{"sku": "C-3", "qty": 3, "price": 5}' FORMAT JSON,
SET '$.items[0].qty' = 4
)
WHERE JSON_VALUE(o.doc, '$.orderId' RETURNING NUMBER) = 1001;The SET '$.items[0].qty' = 4 operation addresses the first array element by position. Positions can shift when elements are added or removed, so prefer a filter or a stable key when the array is long. An out-of-range index with an ERROR ON MISSING handler raises an error. With IGNORE ON MISSING, the operation does nothing.
Choosing the right-hand value
The right-hand side of SET, INSERT, APPEND, and REPLACE can be a SQL value, a bind variable, or a scalar subquery. This lets you copy relational data into a document:
UPDATE orders o
SET o.doc = JSON_TRANSFORM(o.doc,
SET '$.customer.tier' = 'GOLD')
WHERE JSON_EXISTS(o.doc, '$.items[*]?(@.price > 20)');Use bind variables for values that come from users. They keep the statement safe from injection and let Oracle reuse the parsed statement.
JSON_MERGEPATCH
JSON_MERGEPATCH(target, patch) follows the RFC 7396 merge algorithm. The patch describes the desired end state of the parts you want to change. The rules are:
- If a patch member is an object, Oracle merges it recursively into the matching target member.
- If a patch member is any other value, it replaces the target member, or is added if the target has no such member.
- If a patch member is JSON
null, the target member is removed. - An array in the patch replaces the whole target array.
The same status change looks like this as a patch:
UPDATE orders o
SET o.doc = JSON_MERGEPATCH(o.doc,
'{"status": "SHIPPED", "customer": {"city": null}}')
WHERE JSON_VALUE(o.doc, '$.orderId' RETURNING NUMBER) = 1001;The patch sets status, removes customer.city, and leaves customer.name and items untouched.
SELECT JSON_MERGEPATCH(
'{"a": 1, "tags": ["x", "y"], "meta": {"k": 1, "j": 2}}',
'{"tags": ["z"], "meta": {"k": null}, "b": 2}'
) AS result
FROM dual;This returns the document below. Again, key order may differ.
{"a":1,"tags":["z"],"meta":{"j":2},"b":2}Choosing between the two
| Question | JSON_TRANSFORM | JSON_MERGEPATCH |
|---|---|---|
| Edit one array element | Yes | No, it replaces the whole array |
| Append to an array | Yes (`APPEND`) | No |
| Rename or reorder fields | Yes | No |
| Set a field to JSON null | Yes | No |
| Control errors for missing paths | Yes, with handlers | No |
| Apply a patch sent by a client | Awkward | Natural, since the patch is a document |
Common errors and gotchas
- Forgetting the UPDATE. A
SELECTwithJSON_TRANSFORMshows the changed document but leaves the stored one as it was. - Missing
FORMAT JSON. Without it, a text value is stored as a JSON string. A document such as{"sku": "C-3"}becomes a string with escaped quotes instead of an object. - Needing an alias.
UPDATE orders o SET o.doc = ...works. Dot notation on a column requires a table alias, so alias the table in queries too. - Unexpected array replacement. When a merge patch contains an array, all existing elements are lost. Review patches that come from clients before you apply them.
- Filtering by a changed field. The
WHEREclause sees the old document, so a condition onstatusmatches the value from before the update. - Concurrent edits. Two sessions that update the same row serialize on the row lock, and the second applies its change to the committed result of the first. That is safe for changes to different fields, but a later write to the same field wins.
Exercise
What does JSON_MERGEPATCH('{"a":1,"tags":["x","y"],"meta":{"k":1}}', '{"tags":["z"],"meta":{"k":null},"b":2}') return, ignoring key order and spacing?
Show answer
{"a":1,"tags":["z"],"meta":{},"b":2}. The patch array replaces the old array. The null removes "k" and leaves "meta" as an empty object. The new field "b" is added.
Exercise
Write an UPDATE that adds the item {"sku": "D-9", "qty": 1, "price": 12} to the items array of order 1001 and sets $.status to 'PACKED', in one statement. Which function do you use, and why not the other?
Show answer
UPDATE orders o SET o.doc = JSONTRANSFORM(o.doc, APPEND '$.items' = '{"sku": "D-9", "qty": 1, "price": 12}' FORMAT JSON, SET '$.status' = 'PACKED') WHERE JSONVALUE(o.doc, '$.orderId' RETURNING NUMBER) = 1001; You use JSONTRANSFORM because APPEND adds to an array. JSONMERGEPATCH could only replace the whole items array.