1

I have an existing table like that:

id | json
---+----------
1  | {"1":"1"}
2  | NULL

and i want to be able to merge {"2":"2"} into any one of the existing rows wheater or not the json field already contains JSON or is NULL. That it looks like that:

id | json
---+----------
1  | {"1":"1", "2":"2"}
2  | {"2":"2"}

with UPDATE table SET json = CAST('{"2":"2"}' AS JSON) WHERE id=1) I can only update the second row or overwrite the first one.

with UPDATE table SET json = JSON_MERGE(json, CAST('{"2":"2"}' AS JSON) WHERE id=1) I can only update the first row, the second row stays unchanged.

Is there a single command that accounts for both cases?

1 Answer 1

3

One approach would be to COALESCE the current json column to the equivalent of empty string in JSON terms:

UPDATE yourTable
SET json = JSON_MERGE(COALESCE(json, CAST('{}' AS JSON)), CAST('{"2":"2"}' AS JSON))
WHERE id = 1;

Another quick and dirty approach here would be to use a CASE expression to decide whether you merge or simply overwrite:

UPDATE yourTable
SET json = CASE WHEN json IS NOT NULL
                THEN JSON_MERGE(json, CAST('{"2":"2"}' AS JSON))
                ELSE CAST('{"2":"2"}' AS JSON) END
WHERE id = 1;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.