split part Splits Compound Keys

Split compound identifiers like partition-host-index with split_part, and reach fields behind the first or last separator with negative indexes.

SqlData Integrity

Code

snippet
-- 复合键形如 <region>-<rack>-<slot>:region 自身含连字符,槽位才可靠
CREATE TABLE shard_report (shard_key text, requests int);

INSERT INTO shard_report VALUES
    ('us-east-1-a-0', 120),
    ('us-west-2-b-3', 45);

SELECT
    shard_key,
    -- 第 1 段(正索引从 1 开始)
    split_part(shard_key, '-', 1)  AS region,
    -- 最后一段:负索引从末尾倒数(PostgreSQL 14+)
    split_part(shard_key, '-', -1) AS slot,
    split_part(shard_key, '-', -2) AS rack,
    -- 超界返回空串而不是报错
    split_part(shard_key, '-', 99) AS beyond
FROM shard_report;

DROP TABLE shard_report;

Inside the snippet

Several statements share this file — SELECT / INSERT / CREATE, with shard_report among the objects involved.

Using it

The shard_report table is the working surface here.

Key statements

SELECT
shard_key,
split_part(shard_key, '-', 1)  AS region,
split_part(shard_key, '-', -1) AS slot,
split_part(shard_key, '-', -2) AS rack,
split_part(shard_key, '-', 99) AS beyond
FROM shard_report;
INSERT INTO shard_report VALUES
('us-east-1-a-0', 120),
('us-west-2-b-3', 45);
CREATE TABLE shard_report (shard_key text, requests int);

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
The references are `shard_report`.