설문조사
PostgreSQL/PPAS 관련 듣고 싶은 교육은


총 게시물 94건, 최근 0 건
   

array 컬럼 타입

글쓴이 : PostgresDBA 날짜 : 2014-11-06 (목) 18:50 조회 : 7068

SQL> CREATE TABLE ZOO(ANIMAL TEXT[]);

-- 어디까지가 single quote 고 어디가 double quote 인지 잘 살펴보세요.
SQL> INSERT INTO ZOO VALUES ('{"인간"}'), ('{"사자","호랑이"}'), ('{"사슴","토끼","얼룩말"}');
INSERT 0 3

SQL> select * from zoo;
       animal
--------------------
 {인간}
 {사자,호랑이}
 {사슴,토끼,얼룩말}
(3 rows)

-- PostgreSQL 의 배열첨자는 0 이 아니라 1 부터 시작합니다.  주의하세요!
SQL> select animal[0] from zoo;
 animal
--------
 <NULL>
 <NULL>
 <NULL>
(3 rows)


SQL> select animal[1] from zoo;  -- 첫번째 원소를 반환합니다.
 animal
--------
 인간
 사자
 사슴
(3 rows)


SQL> select animal[2] from zoo; -- 두번째 원소를 추출합니다.
 animal
--------
 <NULL>
 호랑이
 토끼
(3 rows)


SQL> select animal[2:3] from zoo;    -- 2~3번째 원소들을 추출합니다. [start:end]
    animal
---------------
 {}
 {호랑이}
 {토끼,얼룩말}
(3 rows)

SQL> select array_upper(animal,1) from zoo;      # 배열 갯수/마지막 원소첨자값(index) 들 반환합니다. 두번째 인자 1은 1차원 배열임을 알려주는겁니다.
 array_upper
-------------
           1
           2
           3
(3 rows)

SQL> select unnest(animal) from zoo;       # 배열을 로우로 변환합니다.
 unnest 
--------
 인간
 사자
 호랑이
 사슴
 토끼
 얼룩말
(6 rows)

배열 관련된 다른 예제들도 살펴보세요.

SQL> select current_date + x from generate_series(1,7) x;
  ?column?
------------
 2014-11-07
 2014-11-08
 2014-11-09
 2014-11-10
 2014-11-11
 2014-11-12
 2014-11-13
(7 rows)

SQL> select array(select current_date + x from generate_series(1,7) x);
                                     array
--------------------------------------------------------------------------------
 {2014-11-07,2014-11-08,2014-11-09,2014-11-10,2014-11-11,2014-11-12,2014-11-13}
(1 row)


SQL> select array_agg(current_date + x)  from generate_series(1,7) x;
                                   array_agg
--------------------------------------------------------------------------------
 {2014-11-07,2014-11-08,2014-11-09,2014-11-10,2014-11-11,2014-11-12,2014-11-13}
(1 row)



   

postgresdba.com