0
1

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で空配列を返したい

0
Last updated at Posted at 2021-10-21

経緯

json_agg関数array_agg関数を使ってSQLからJSONを返す処理を実装していたが、特定条件の場合、CASE式で空配列を返す処理が必要になって、試行錯誤することになった。基本使わないと思うが、なかなか苦労したのでメモとして残す。

結論

-- 空配列を返す。配列の型は宣言する必要がある
SELECT ARRAY[]::VARCHAR[] AS empty_array;

試行錯誤メモ

-- [null]が返ってくる。nullが入った配列であり、空配列ではない
SELECT ARRAY[NULL] AS null_array;

-- 上記からnullを削除する。空配列が返ってくるけど、処理効率は悪そう
-- ちなみにpg_typeof関数にかけたらtext[]が返ってくる
SELECT array_remove(ARRAY[NULL], NULL) AS bad_empty_array;

-- 型宣言がないとエラーになる
SELECT ARRAY[] AS error;
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?