Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql - Check if a given string starts with any element of the array of strings

Given two strings we can do:

select 'aaa123' ilike 'aaa'||'%'

The result will be TRUE. I would like to do the same thing with a string and an array - if the given string starts with any of the elements of the array of strings than the result would show TRUE.

For example (array and string):

select array['aaa123'::text,'bbb123'::text] as text_array
select 'aaa12345' as string

I would like to do something like this:

select string ilike ANY(text_array || '%')

And I would expect TRUE since aaa12345 starts with aaa123 (element of the array).

Thanks a lot for the help!

like image 392
postgresql_beginner Avatar asked Aug 18 '16 13:08

postgresql_beginner


2 Answers

You could unnest() the array of strings and then compare your input string with every element like you wanted.

You would get as many rows in the output as there are elements in your array. Since you need a clear indicator whether any of the comparison against array element yields true use bool_or() aggregate function:

select 
  bool_or('string12345' ilike arr_element||'%') 
from 
  unnest(ARRAY['string123','something']::text[]) x(arr_element);

This would give you TRUE since:

SELECT 'string12345' ilike 'string123%' -- true

Note: bool_or() returns true if at least one input value is true, otherwise false.

like image 199
Kamil Gosciminski Avatar answered Sep 22 '22 17:09

Kamil Gosciminski


select string ilike ANY(
    select s || '%'
    from unnest(text_array) s(s)
    )
like image 40
Clodoaldo Neto Avatar answered Sep 19 '22 17:09

Clodoaldo Neto