0
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?

PostgreSQL の array_agg() で select 結果を配列に格納

0
Posted at

やりたいこと

select した結果を配列で取得する。
例えば select の結果が 1、2、3 の場合、配列の [1, 2, 3] として検索結果を取得する。

select の結果を配列で取得

テーブル定義例

create table test1 (
  id    integer generated always as identity primary key,
  name  varchar(32) not null
);

insert into test1 (name) values ('aaa');
insert into test1 (name) values ('bbb');
insert into test1 (name) values ('ccc');

array_agg()

array_agg({フィールド}) で select の結果を配列として取得することができる。

# select
  array_agg(name order by name)
from
  test1;

   array_agg
---------------
 {aaa,bbb,ccc}
(1 row)

select 結果が空の場合には null が返却される。

# select
  array_agg(name order by name)
from
  test1
where
  id = 4;

 array_agg
-----------

(1 row)

select 結果が空の場合に空の配列を返すようにするには、
coalesce() で null の場合に空の配列を指定する。

select
  coalesce(array_agg(name order by name), array[]::varchar[])
from
  test1
where
  id = 4;

 coalesce
----------
 {}
(1 row)

配列の n 番目の値を参照するには、[n] で要素を指定する。

# select
  (array_agg(name order by name))[1]
from
  test1;

 array_agg
-----------
 aaa
(1 row)
0
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
0
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?