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 3 years have passed since last update.

PostgreSQLで配列の値がNULLもしくは空の場合はtrueとなる関数を作る

Posted at

はじめに

PostgreSQLでは配列の長さを返す関数は空配列の場合NULLを返します。

SELECT array_length('{}'::TEXT[], 1) IS NULL;
 ?column? 
----------
 t
(1 row)

空配列をチェックする場合は以下のようになりますが、意味がわかりにくいです。

IF p_array IS NULL OR array_length(p_array, 1) IS NULL THEN

そこで関数を作成しました。

プログラム

-- 配列が空かどうかチェックする
-- 引数
--   p_array : 配列
-- 戻り値
--   配列が空の時true
CREATE OR REPLACE FUNCTION is_array_empty(
  p_array anyarray
) RETURNS BOOLEAN AS $$
DECLARE
BEGIN
  RETURN p_array IS NULL OR ARRAY_LENGTH(p_array, 1) IS NULL;
END;
$$ LANGUAGE plpgsql;

使ってみると一目瞭然です。

IF is_array_empty(p_array) THEN
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?