Skip to content

Instantly share code, notes, and snippets.

@gelin
Created February 20, 2020 15:51
Show Gist options
  • Save gelin/3f55efa818ff2f8070cfa863730846e7 to your computer and use it in GitHub Desktop.
Save gelin/3f55efa818ff2f8070cfa863730846e7 to your computer and use it in GitHub Desktop.
jsonb_set example

What is the result of this?

SELECT jsonb_set('{}', '{test}', to_jsonb((SELECT 'test' LIMIT 0)::text));

SELECT to_jsonb((SELECT 'test' LIMIT 0)::text);

Returns null.


SELECT to_jsonb(null::text);

Also returns null.


SELECT jsonb_set('{}', '{test}', null);

Also, Mother Nature, returns null, even when we get not-null document and trying to add null there.


The correct null should be added like this:

SELECT jsonb_set('{}', '{test}', 'null');

Here you get the expected {"test": null}.


Here is the complete example which adds null to the document or a value depending of the result of the nested query.

SELECT jsonb_set('{}', '{test}', COALESCE(to_jsonb((SELECT 'test' LIMIT 0)::text), 'null'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment