StringsPostgreSQL only

SPLIT_PART

Splits a string by a separator and returns the part with the number you need.

Syntax

SPLIT_PART(<text>, <separator>, <part number>)

Cuts the text into pieces at the separator and returns the piece with the given number, counting from 1. A negative number counts from the end: -1 is the last part. Handy for text with a predictable structure: the domain of an email, the country code of a phone number, part of a path.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

Login and domain from an email
SELECT SPLIT_PART('emma@example.com', '@', 1) AS login,
SPLIT_PART('emma@example.com', '@', 2) AS domain;
logindomain
emmaexample.com
The last part — with a negative number
SELECT SPLIT_PART('backend/api/v2', '/', -1) AS last_part;
last_part
v2
The country code from a phone number
SELECT name, phone,
SPLIT_PART(phone, ' ', 1) AS country_code
FROM employees;
namephonecountry_code
Emma+44 7700 900123+44
LiamNULLNULL
Olivia+44 7700 900456+44
Noah+44 7700 900789+44
SophiaNULLNULL

Unlike SUBSTRING, you don't need to know the length of the code: everything up to the first space is taken.

Watch out

If there's no part with that number, the result is an empty string '', not NULL: SPLIT_PART('a,b', ',', 5).

Part number 0 is an error, field position must not be zero: numbering starts at 1.

Only the separator itself is cut, surrounding spaces stay: SPLIT_PART('a, b', ',', 2) gives b with a leading space. TRIM will remove it.