5

I Need to extract values from string with Postgresql But for my special scenario - if an element value is null i want to remove it and bring the next element 1 index closer.

e.g. 
 assume my string is: "a$$b"

If i will use

select string_to_array('a$$b','$')

The result is:

{a,,b}

If Im trying

SELECT unnest(string_to_array('a__b___d_','_')) EXCEPT SELECT ''

It changes the order

1.d
2.a
3.b

order changes which is bad for me.

I have found a other solution with:

select array_remove( string_to_array(a||','||b||','||c,',') , '')
from (
select
split_part('a__b','_',1) a,
split_part('a__b','_',2) b,
split_part('a__b','_',3) c
)  inn

Returns

{a,b}

And then from the Array - i need to extract values by index e.g. Extract(ARRAY,2)

But this one seems to me like an overkill - is there a better or something simpler to use ?

1 Answer 1

2

You can use with ordinality to preserve the index information during unnesting:

select a.c
from unnest(string_to_array('a__b___d_','_')) with ordinality as a(c,idx)
where nullif(trim(c), '') is not null
order by idx;

If you want that back as an array:

select array_agg(a.c order by a.idx)
from unnest(string_to_array('a__b___d_','_')) with ordinality as a(c,idx)
where nullif(trim(c), '') is not null;
Sign up to request clarification or add additional context in comments.

Comments

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.