Regexp Split To Table Rows
Explode free-form tag lists into rows with regexp_split_to_table behind a LATERAL join; a [,;\s]+ delimiter absorbs the mixed separators split_part preserves.
Code
CREATE TABLE docs (
id int PRIMARY KEY,
tags text NOT NULL
);
INSERT INTO docs VALUES
(1, 'postgres,window,performance'),
(2, 'sql; index'),
(3, 'planner, vacuum');
-- regexp_split_to_table 是集合返回函数,LATERAL 引用外层的 d.tags;
-- 分隔符 [,;s]+ 把逗号、分号、空格混写一次归一,一行一个 tag
SELECT d.id, t.tag
FROM docs d,
LATERAL regexp_split_to_table(d.tags, '[,;\s]+') AS t(tag)
ORDER BY d.id, t.tag;
-- 对照 split_part:只取固定第 N 段,分隔符与多余空格原样保留
SELECT id,
split_part(tags, ',', 1) AS first_tag,
split_part(tags, ',', 2) AS second_tag
FROM docs
ORDER BY id;Inside the snippet
What runs here is SELECT / INSERT / CREATE — docs are the objects involved.
Breaking the statements into their working parts: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Using it
Run the statement against the docs table.
Key statements
SELECT id,
split_part(tags, ',', 1) AS first_tag,
split_part(tags, ',', 2) AS second_tag
FROM docs
ORDER BY id;
SELECT d.id, t.tag
FROM docs d,
LATERAL regexp_split_to_table(d.tags, '[,;\s]+') AS t(tag)
ORDER BY d.id, t.tag;
INSERT INTO docs VALUES
(1, 'postgres,window,performance'),
(2, 'sql; index'),
(3, 'planner, vacuum');
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.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.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.
FAQ
- Which tables does this file reference?
- `docs`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.