[DB] 문자열 다루기 (split_part, array_to_string, array_agg)

Jisoo Choi·2021년 10월 20일
0

Database

목록 보기
2/5

쿼리를 만들면서 문자열의 특정 요소만 추출하는 작업을 할 때가 있다.
주로 사용하는 문법으로 3가지가 있다.
split_part, array_to_string, array_agg

💡 Split_part: 문자열 분해

  • 다음은 문자열을 분해할 때 사용하는 함수다.

[Syntax]
SPLIT_PART(문자열, 자를문자, 위치)

[Example]

SELECT split_part('A,B,C', ',', 2);

Sample Output:

split_part
-----------
 B

💡 Substring: 문자열 추출

[Syntax]
SUBSTRING(string [from <추출이 시작되는 곳>][for <**추출글자** 개수>])

[Example]

SELECT substring('substring test' FROM 1 FOR 3);

Sample Output:

substring
----------
 sub

💡 Concat: 문자열 합치기

  • string 또는 field를 붙일 경우 사용하는 함수다.

[Syntax]
CONCAT(앞문자열, 중간삽입글자(옵션), 뒷문자열)

[Example]

SELECT concat('문자열', '합치기');  -- 문자열합치기

➕ 문자열 합치기로 "||" (operator) 도 있다.

  • 단, 주의해야할 점은 PostgreSQL에서는 NULL을 인지하기 때문에 합치려는 값 중에 하나라도 NULL이 존재할 경우 NULL을 반환한다!

    SELECT '문자열' || '합치기'  --문자열합치기
    
    SELECT '문자열' || NULL || '합치기'  -- NULL


Reference

https://www.postgresqltutorial.com/postgresql-split_part/

https://www.postgresqltutorial.com/postgresql-concat-function/

https://ysyblog.tistory.com/131

profile
👩‍🚀 No worries! Just record

0개의 댓글