array_length() of an empty array returning NULL array_length() of an empty array returning NULL arrays arrays

array_length() of an empty array returning NULL


As always, if you want to have different behavior for NULL values, use the coalesce construct:

FOR i IN 1..coalesce(array_length(array, 1), 0) LOOP    RAISE NOTICE '%', array[i];END LOOP;

As for the return value: array_length(x, N) returns the number of elements in Nth dimension. Since an empty array has no dimensions, it returns NULL. You're right that it's counterintuitive if you only consider simple arrays, but makes sense for multi-dimensional arrays.

Edit: Like Erwin Brandstetter wrote in the comments, it's more correct to use array_lower/upper to loop over array indices. These will work for arrays that are not 1-based. These also take a dimension argument and require coalesce:

FOR i IN coalesce(array_lower(array, 1), 1)..coalesce(array_upper(array, 1), 1) LOOP    RAISE NOTICE '%', array[i];END LOOP;


Avoid the problem altogether by looping through the array with FOREACH, introduced with Postgres 9.1:

FOREACH i IN ARRAY $1LOOP   -- do somethingEND LOOP;

Depending on what you want to do inside the loop, you might be able to avoid looping altogether and use plain SQL with unnest() instead. Set-based operations are typically faster than looping in PostgreSQL.

Example:

RETURN QUERYSELECT elem || 'foo'FROM unnest($1) AS t(elem);