Database

PostgreSQL 배열 함수

hjkang

PostgreSQL은 다양한 배열 함수를 지원한다.

그 중 자주 사용하는 배열 함수 몇 가지를 알아보자.

 

 

설명 위한 테이블 & 데이터 생성

create table table1 (
    col1  text,
    col2  integer[]
);
insert into table1 values ('Bill', '{10000, 10000, 10000, 10000}');
insert into table1 values ('Carol', '{20000, 25000, 25000, 25000}');

create table table2 (
    col1  text,
    col2  text
);
insert into table2 values ('A', 'A1');
insert into table2 values ('A', 'A2');
insert into table2 values ('A', 'A3');
insert into table2 values ('B', 'B1');
insert into table2 values ('B', 'B2');
insert into table2 values ('B', 'B3');

 

 

unnest()

  • array 데이터를 row로 변환한다.
  • sum() 같은 집계 함수와 같이 사용하면 array의 개수만큼 값이 중복되어 원치 않는 값이 발생할 수 있다.
select
    col1,
    unnest(col2) as col2
from table1;

 

 

array_agg()

  • row를 array로 변환한다.
  • group by 된 값들을 array로 반환한다.
  • distinct 와 order by를 같이 사용하여 중복 제거된 값을 구하거나, 원하는 순서로 정렬하여 array를 만들 수 있다.
    • array_agg(distinct col2 order by col2)
select
    col1,
    array_agg(col2) col2
from table2
group by col1;

 

 

array_to_string()

  • array를 string으로 변환한다.
  • 구분자로 구분지을 수 있다.
select
    col1,
    array_to_string(array_agg(col2),',') col2
from table2
group by col1;

 

 

string_to_array()

  • string을 특정 문자로 분리하여 array로 변환한다.
  • split 기능이다.
insert into table2 values ('C', 'C1,C2,C3');

select
    col1,
    string_to_array(col2, ',') col2
from table2
where col1 = 'C';

 

 

 

 


참고

- https://codecamp.tistory.com/9

 

 

 

 

'Database' 카테고리의 다른 글

PostgreSQL UNION, UNION ALL  (0) 2023.05.15
PostgreSQL 인덱스를 타지 않는 이유  (0) 2023.05.11
PostgreSQL 문자열 함수  (0) 2023.05.11
PostgreSQL 함수(Function)  (0) 2023.05.10
PostgreSQL GIN Index  (0) 2023.01.30