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.
Code
-- 复合键形如 <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
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.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.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 relations does the SQL touch?
- The references are `shard_report`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.