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.
Code
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
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.LLM Token & Cost EstimatorEstimate BPE-approximate LLM token counts across English, CJK text, and source code and compare request and batch costs across pricing tiers.
FAQ
- Which objects does the SQL touch?
- `articles` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.