Intro
Let's assume you have a table with a column j
of type JSON
and for that column you have a nested property that is nullable. Example:
{"hello": "world"}
{"hello": null}
...
In MySQL 5.7.13+, the easiest way to select the hello
values would be with something like this:
SELECT j->>'$.hello' FROM ...
However, the result of that query would have null
string (LONGTEXT
) values instead of the special SQL NULL
values:
world -- that's a string
null -- that's also a string
...
One way to verify that would be to run something like:
SELECT COALESCE(j->>'$.hello', 'YouWillNeverSeeMe:(((')
What might look even stranger is that if we used ->
instead of ->>
, we'd get:
"world" -- that's a string (note the quotation marks)
null -- that's also a string (with no quotation marks)
...
Solution
So how do we get the JSON null
values as SQL NULL
values?
MySQL 8.0.21+
In MySQL 8.0.21+ we can use the JSON_VALUE function and do something like this:
SELECT JSON_VALUE(j->'$.hello', '$') FROM ...
The result would be:
world -- that's a string
[NULL] -- that's NOT a string but the special SQL NULL value
...
Note that if we used ->>
instead of ->
here, we would fetch:
[NULL] -- that's NOT a string but the special SQL NULL value
[NULL] -- that's NOT a string but the special SQL NULL value
...
Older MySQL (incl. 5.7)
I am not aware of an ideal solution. The answer provided by sergolius looks simple and nice, but it has a potential flaw one should consider. Let's say Alice and Bob were blessed with a kid and they decided to name it Null (hey, I'm not here to judge!). And let's say Null ended up in our DB's JSON column. So instead of fetching:
Alice
[NULL]
Bob
Null
John
...
, we might end up with:
Alice
[NULL]
Bob
[NULL] -- Oops! Where did Null go?
John
...
SELECT COALESCE(JSON_EXTRACT(JSON_OBJECT("hello", NULL), '$.hello'), 'world')
– Euterpe