2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

PostgreSQLのarray_lengthが微妙な動きをするのでラップする関数を作る

Posted at

目的

PostgreSQLで配列の長さを返す関数がちょっと直感と反する動きをします。

test=# select array_length(ARRAY[1]::BIGINT[], 1);
 array_length 
--------------
            1
(1 )
test=# select array_length(ARRAY[]::BIGINT[], 1);
 array_length 
--------------
(1 )
test=# select array_length(NULL::BIGINT[], 1);
 array_length 
--------------
(1 )

空配列もNULLも0を返してほしいです。
ちなみにこうするとうまくいきます。

test=# select coalesce(array_length(ARRAY[]::BIGINT[], 1), 0);
 coalesce 
----------
        0
(1 )

これ全部書くと長いのでストアードプロシージャを作ってラップします。

コード

CREATE OR REPLACE FUNCTION uv_array_length(
  p_target_array ANYARRAY
  ,p_dimension INT DEFAULT 1 
) RETURNS BIGINT AS $FUNCTION$
DECLARE
BEGIN
  RETURN COALESCE(array_length(p_target_array, p_dimension), 0);
END;
$FUNCTION$ LANGUAGE plpgsql STABLE;
test=# select uv_array_length(ARRAY[]::BIGINT[]);
 uv_array_length 
-----------------
               0
(1 )
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?