이번 포스팅에서는 PostreGQL, Greenplum DB에서 SQL 함수를 사용하여 문자열의 일부분을 가져오는 두가지 함수를 비교하여 소개하겠습니다. 

 

(1) 위치 기반(position based)으로 문자열의 일부분 가져오기: SUBSTRING(), SUBSTR()

(2) 구분자를 기반(delimiter based)으로 문자열을 분할하여 일부분 가져오기: SPLIT_PART()

 

PostgreSQL, Greenplum: SUBSTR(), SPLIT_PART()

 

SUBSTR() 함수는 문자열의 포맷이 일정하게 정해져 있어서 위치를 기반으로 문자열의 특정한 일부분만 가져올 때 사용합니다. 반면에, SPLIT_PART() 함수는 문자열에 구분자(delimiter)가 있어서, 이 구분자를 기준으로 문자열을 구분한 후에 특정 순서에 위치한 문자열의 일부분을 가져올 때 사용합니다. 

 

아래에 간단한 예를 들어서 설명하겠습니다. 

 

 

(1) 위치 기반(position based)으로 문자열의 일부분 가져오기: SUBSTRING(), SUBSTR()

 

- syntax: SUBSTR(문자열, 시작 위치, 가져올 문자 개수)

 

substr() 함수와 substring() 함수는 동일합니다. 

 

---------------------------------------------
-- String functions in PostgreSQL
-- substr() vs. split_part()
---------------------------------------------

-- (1) substr(string, from [, count])
-- : Extract substring
-- : when position is fixed

SELECT 
	SUBSTR('abc_def_01', 1, 3) AS substr_1
	, SUBSTR('abc_def_01', 5, 3) AS substr_2
	, SUBSTR('abc_def_01', 9, 2) AS substr_3;

--substr_1|substr_2|substr_3|
----------+--------+--------+
--abc     |def     |01      |


-- or equivalently  (same as substring(string from from for count))
SELECT 
	SUBSTRING('abc_def_01', 1, 3) AS substr_1
	, SUBSTRING('abc_def_01', 5, 3) AS substr_2
	, SUBSTRING('abc_def_01', 9, 2) AS substr_3;

 

 

 

 

(2) 구분자를 기반(delimiter based)으로 문자열을 분할하여 일부분 가져오기: SPLIT_PART()

 

- syntax: SPLIT_PART(문자열, 구분자 텍스트, 가져올 필드 순서)

 

-- (2) split_part(string text, delimiter text, field int)
-- : Split string on delimiter and return the given field (counting from one)
-- : when deliiter is fixed

SELECT 
	SPLIT_PART('abc_def_01', '_', 1) AS split_part_1
	, SPLIT_PART('abc_def_01', '_', 2) AS split_part_2
	, SPLIT_PART('abc_def_01', '_', 3) AS split_part_3;

--split_part_1|split_part_2|split_part_3|
--------------+------------+------------+
--abc         |def         |01          |

 

 

[ Reference ]

* PostgreSQL string functions and operators
: https://www.postgresql.org/docs/9.1/functions-string.html

 

 

이번 포스팅이 많은 도움이 되었기를 바랍니다. 

행복한 데이터 과학자 되세요!

 

728x90
반응형
Posted by Rfriend
,