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.
Code
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.