String To Array Token Roundtrip

Tokenize a delimited column with string_to_array, filter with = ANY, and rebuild text with array_to_string, where a null string turns empty fields into NULL.

SqlData Fetching

Code

snippet
CREATE TABLE articles (
    id   int PRIMARY KEY,
    tags text NOT NULL  -- 逗号分隔的标签串
);

INSERT INTO articles VALUES
    (1, 'sql,index,scan'),
    (2, 'planner,vacuum'),
    (3, 'sql');

SELECT
    id,
    -- string_to_array:按分隔符 token 化成 text[]
    string_to_array(tags, ',') AS tag_array,
    -- 第三个参数:等于它的空段显式变 NULL
    string_to_array('a,,b', ',', '') AS nullstr_demo,
    -- 数组成员匹配:= ANY
    'sql' = ANY(string_to_array(tags, ',')) AS has_sql_tag
FROM articles
ORDER BY id;

-- array_to_string:数组拼回文本完成 roundtrip;NULL 元素可用占位符
SELECT array_to_string(string_to_array('a,,b', ','), '|') AS empty_kept,
       array_to_string(string_to_array('a,,b', ',', ''), '|', '-') AS null_as_dash;

How the snippet works

The file runs SELECT / INSERT / CREATE statements, touching articles.

Mechanically, the statements are built from: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

The articles table is the working surface here.

Statements that matter

SELECT
    id,
    string_to_array(tags, ',') AS tag_array,
    string_to_array('a,,b', ',', '') AS nullstr_demo,
    'sql' = ANY(string_to_array(tags, ',')) AS has_sql_tag
FROM articles
ORDER BY id;
SELECT array_to_string(string_to_array('a,,b', ','), '|') AS empty_kept,
       array_to_string(string_to_array('a,,b', ',', ''), '|', '-') AS null_as_dash;
INSERT INTO articles VALUES
    (1, 'sql,index,scan'),
    (2, 'planner,vacuum'),
    (3, 'sql');

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`articles` — referenced directly, no join needed.