14

How can I coalesce a null column into an empty JSONB array? This doesn't work:

SELECT jsonb_array_elements(coalesce(null_column, '{}'::jsonb))
FROM table
WHERE id = 13;

-- ERROR:  cannot extract elements from an object

Neither this:

SELECT jsonb_array_elements(coalesce(null_column, '[]'::jsonb))
FROM table
WHERE id = 13;

-- ERROR:  cannot extract elements from a scalar
1
  • 2
    It really depends on the exact definition of null_column, the data allowed in it and your version of Postgres. Commented Dec 17, 2016 at 7:16

2 Answers 2

11

{} is an object but jsonb_array_elements expects an array, so replace {} with []

Make sure that both arguments return a jsonb array. For example, if your column is an integer, you can use concat to add the square brackets and ::jsonb for the conversion

SELECT jsonb_array_elements(coalesce(concat('[',my_column,']')::jsonb,'[]'::jsonb))
Sign up to request clarification or add additional context in comments.

5 Comments

This works nice but for some weird reason, I still get cannot extract elements from a scalar if I use my column name instead of null.
@norbertpy forgot to address that - you will have to convert the column value to an json array because both arguments in the coalesce must return a json array
My column is JSONB for sure, but seems like Postgres cannot tell it's null. Even this SELECT (CASE WHEN col IS NULL THEN 'is-null' ELSE 'is-not-null' END) AS r FROM t WHERE id = 13; returns is-not-null.
But that will be another question. Thanks for the inputs.
@norbertpy are you sure col should be null as opposed to the string that represents null in json?
4

Here is SQL code for accomplishing what you want:

SELECT jsonb_array_elements(coalesce(null_column, '[{}]'::jsonb))
FROM table
WHERE id = 13;

2 Comments

for just an empty array I think it's more like, '[]'::jsonb but thanks, you got me there with your answer
Could you add a bit of explanation? I'm just starting to work with postgres's jsonb functions, and don't quite get the [{}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.