Recursive CTE Split Delimited String

Split a delimited string with a recursive CTE that peels one token per iteration, and prefer the built-in string_to_table on PostgreSQL 14 and later.

SqlData Integrity

Code

snippet
-- 反范式遗留表:channels 存成逗号 delimited 串,目标是拆成一行一个渠道
CREATE TABLE integrations (
    id       bigserial PRIMARY KEY,
    service  text NOT NULL,
    channels text NOT NULL
);
INSERT INTO integrations (service, channels) VALUES
    ('checkout', 'web,mobile,api'),
    ('ledger',   'api');

-- 递归 CTE 每轮剥掉一个已消费的前缀:split_part 取首段,剩余串为空即终止
WITH RECURSIVE split(service, tag, rest) AS (
    SELECT service, '', channels
    FROM integrations
    UNION ALL
    SELECT service, split_part(rest, ',', 1),
           substr(rest, length(split_part(rest, ',', 1)) + 2)
    FROM split
    WHERE rest <> ''
)
SELECT service, tag FROM split WHERE tag <> '' ORDER BY service, tag;

-- PostgreSQL 14+ 有内建 set-returning 函数:简单拆分不必手写递归 CTE
SELECT service, channel
FROM integrations CROSS JOIN LATERAL string_to_table(channels, ',') AS t(channel);

What the code does

Several statements share this file — SELECT / INSERT / CREATE, with integrations, split and lateral among the objects involved.

What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; a UNION combining result sets from separate queries; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

Run the statement against the integrations table.

Statements that matter

WITH RECURSIVE split(service, tag, rest) AS (
SELECT service, '', channels
FROM integrations
UNION ALL
SELECT service, split_part(rest, ',', 1),
substr(rest, length(split_part(rest, ',', 1)) + 2)
FROM split
WHERE rest <> ''
)
SELECT service, tag FROM split WHERE tag <> '' ORDER BY service, tag;
SELECT service, channel
FROM integrations CROSS JOIN LATERAL string_to_table(channels, ',') AS t(channel);
CREATE TABLE integrations (
id       bigserial PRIMARY KEY,
service  text NOT NULL,
channels text NOT NULL
);

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`integrations`, `split`, `lateral` — joined via one JOIN clause.