Why casting JSONb NULL to a type fails, it is a specification bug?

0

As commented in this answer,

SELECT (j->'i')::int FROM  (SELECT '{"i":null}'::jsonb) t(j); -- fail

results in "ERROR: cannot cast jsonb null to type integer"... Ok, this is the "PostgreSQL way", but why not make it better? Better than add CASE clauses, it is doing the "natural" thing, that is casting a JSON-NULL value to a SQL typed null value. So, it is not an implementation problem, but it seems a specification bug in PostregSQL: it is?

casting jsonb postgresql
2021-11-16 19:53:05
1

2

The reason is that SQL NULL is quite different from JSON null.

If you want to do this:

SELECT nullif((j->'i'), 'null')::int FROM  (SELECT '{"i":null}'::jsonb) t(j);
 nullif 
--------
   NULL
(1 row)

 SELECT pg_typeof(nullif((j->'i'), 'null')::int) FROM  (SELECT '{"i":null}'::jsonb) t(j);
 pg_typeof 
-----------
 integer


SELECT nullif((j->'i'), 'null')::int FROM  (SELECT '{"i": 1}'::jsonb) t(j);
 nullif 
--------
      1
(1 row)

Use NULLIF to transform JSON null to SQL NULL.

2021-11-17 05:29:10

In other languages

This page is in other languages

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................