Loop over an PostgreSQL array within a SELECT query, instead of within a PLPGSQL function
I have a text[] ARRAY column within a PostgreSQL table and I need to run char_length() on each element inside the array within a SELECT query (normal SQL, not plpgsql) so that if any of the elements is more than 25 characters long, 开发者_如何学JAVAthe SELECT returns 't' and 'f' otherwise. I know I can loop over the text[] within a custom plpgsql function but due to other reasons I need to find a way to do this in SQL directly.
Is it possible?
As of PostgreSQL 8.4, you can use the UNNEST
function:
SELECT MAX((char_length(string) > 25)::INT)::BOOLEAN
FROM (
SELECT my_array,UNNEST(my_array) AS string
FROM my_table
) AS x
GROUP BY my_array;
You could use unnest
to break open the array and then some simple length
and exists
stuff:
select exists(
select 1
from (
select unnest(ar) as x
from table_name
) as t
where length(x) > 25
)
The exists
and select 1
business is just a convenient way to collapse result set to a single boolean (I'm sure there are other ways).
精彩评论