1

I got a table that has a JSON field. The default value for the field is "NULL" - now I'd like to update a single field of the JSON data.

   | ----------------- |
   | [int]  |   [JSON] |
   |  xy    |   ipdata |
   | ----------------- |

So the field could be something like this:

{ ip: "233.233.233.233", "data": "test", "name": "Peterson", "full_name": "Hanson Peterson" }

So I'd like to update the IP.

update table set ipdata = JSON_SET(ipdata, "$.ip", "newIp") where xy = 2;

But what happens if the field is NULL? The query above does not seems to "create" a new JSON with just the field IP. It just does nothing.


How can I tell mySql to insert the {"ip": "newIp"} if the field is empty and otherwise just update the ip json key?

1 Answer 1

2

You can use Case .. When to handle Null. When the field is null, you can instead create Json_object() and set it:

UPDATE table 
SET ipdata = CASE WHEN ipdata IS NULL THEN JSON_OBJECT("ip", "newIp") 
                  ELSE JSON_SET(ipdata, "$.ip", "newIp") 
             END 
WHERE xy = "xy";
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.