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.

SqlData Fetching

Code

snippet
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

FAQ

Which tables does this file reference?
`docs`.