I am trying to understand handling null
s in PostgreSQL's jsonb
type. Because of
# select 'null'::jsonb is null;
?column?
----------
f
(1 row)
I assume that they are different than SQL null
s (which makes sense) - according to the manual,
SQL NULL is a different concept.
Therefore, these two queries are not surprising at all:
# select '{"a": 1, "b": null}'::jsonb->'b' is null;
?column?
----------
f
(1 row)
# select '{"a": 1, "b": null}'::jsonb->'c' is null;
?column?
----------
t
(1 row)
per the manual:
The field/element/path extraction operators return NULL, rather than failing, if the JSON input does not have the right structure to match the request; for example if no such element exists.
Where the surprise begins, however, is this:
# select '{"a": 1, "b": null}'::jsonb->>'b' is null;
?column?
----------
t
(1 row)
# select '{"a": 1, "b": null}'::jsonb->>'c' is null;
?column?
----------
t
(1 row)
The latter one I can understand - we get an SQL null
from the extraction, and casting a null
to text
leaves it as null
- I assume ->>
works that way, as the manual says
The field/element/path extraction operators return the same type as their left-hand input (either json or jsonb), except for those specified as returning text, which coerce the value to text.
(BTW, I could not find a confirmation that casting an SQL null
to any other type yields null
again in PostgreSQL - is it written somewhere explicitly?)
But the former is a mystery to me. The extraction should get me a jsonb
null
, and I thought casting to text
should give me 'null'
(i.e., a string saying "null"), just like
# select ('null'::jsonb)::text;
text
------
null
(1 row)
But yet it returns a proper SQL null
.
Why is that so?
'null'
, like inselect ('null'::jsonb)::text;
...