split_part Extracts Delimited Fields

split_part pulls the Nth field from a delimited string, counts negative indexes from the end, and returns an empty string past the last field.

SqlData Integrity

Code

snippet
WITH hosts AS (
    SELECT * FROM (VALUES
        ('db-1.internal.example.com'),
        ('cache.example.com'),
        ('localhost')
    ) AS t(host)
)
SELECT
    host,
    -- fields count from 1
    split_part(host, '.', 1) AS first_label,
    -- negative indexes count from the end (PG 14+)
    split_part(host, '.', -1) AS tld,
    -- past the last field an empty string returns, no error
    split_part(host, '.', 5) AS missing
FROM hosts;

What the demo extracts

Three hosts with different depths run through split_part on the dot separator. Field 1 grabs the first label, db-1, cache and localhost; field -1 counts from the end (PG 14+), printing com as the TLD for all three.

Field 5 goes past the last dot for every host, and the function returns the empty string instead of erroring; the printed missing column is blank everywhere, which makes missing-field handling a non-event in queries.

Points worth noting

  • Indexes are 1-based; 0 is invalid.
  • Negative indexes arrived in PostgreSQL 14.

Interactive Tools for This Topic

FAQ

What does split_part return past the end?
An empty string, not an error; field 5 on localhost prints blank in the demo, so absent fields need no special-case SQL.