Question

I have some data in a jsonb col that I need to clean and insert into another text array column.

What I have:

[
  {
    "v": "birthday"
  },
  {
    "v": "reference"
  }
]

What I want (_text):

{birthday, reference}

My query:

select array[col -> 0 ->> 'v', col-> 1 ->> 'v'] from src

gives the expected result as above.

However, when the value is null, I want the value not to be inserted i.e. no NULL value nor empty:

[
  {
    "v": "birthday"
  }
]

should result in

{birthday}

and not

{birthday, [NULL]} -- NULL value
{birthday,} -- Empty string with coalesce

How do you conditionally insert an element into an array when creating one, based on the value of the element?

Was it helpful?

Solution

array_remove() seems to answer my use case (by removing in a 2nd step the null values):

select array_remove(array[col -> 0 ->> 'v', col-> 1 ->> 'v'], null) from src
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top