string_to_table Splits Text Into Rows
Split one delimited column into one row per token with string_to_table, from empty segments to a null_string that turns matching fields into NULL.
Code
CREATE TABLE import_rows (
id int PRIMARY KEY,
raw_tags text
);
INSERT INTO import_rows VALUES
(1, 'urgent,billing,audit'),
(2, 'urgent,,audit');
-- 基本拆分:一行一个 token
SELECT id, tag
FROM import_rows, LATERAL string_to_table(raw_tags, ',') AS t(tag)
WHERE id = 1;
-- 连续分隔符产出空段:'urgent,,audit' 里的空段原样保留
SELECT id, tag, tag = '' AS is_empty
FROM import_rows, LATERAL string_to_table(raw_tags, ',') AS t(tag)
WHERE id = 2;
-- 第三参数 null_string:匹配的字段被替换成 NULL
SELECT id, tag
FROM import_rows, LATERAL string_to_table(raw_tags, ',', 'audit') AS t(tag)
WHERE id = 1;
-- 分隔符为 NULL:每个字符各成一行;分隔符为空串:整串作为单一字段
SELECT tag FROM string_to_table('abc', NULL) AS t(tag);
SELECT tag FROM string_to_table('a,b', '') AS t(tag);
-- WITH ORDINALITY 附加段序号,便于还原拆分前的顺序
SELECT id, ord, tag
FROM import_rows, LATERAL string_to_table(raw_tags, ',') WITH ORDINALITY AS t(tag, ord)
WHERE id = 1;Inside the snippet
SELECT / INSERT / CREATE statements share the script, touching import_rows and string_to_table.
The SQL constructs in play: a WHERE clause limiting a statement to the rows that qualify; a PRIMARY KEY that enforces row identity.
Putting it to use
The import_rows table is the working surface here.
Core lines
SELECT id, ord, tag
FROM import_rows, LATERAL string_to_table(raw_tags, ',') WITH ORDINALITY AS t(tag, ord)
WHERE id = 1;
SELECT id, tag, tag = '' AS is_empty
FROM import_rows, LATERAL string_to_table(raw_tags, ',') AS t(tag)
WHERE id = 2;
SELECT id, tag
FROM import_rows, LATERAL string_to_table(raw_tags, ',', 'audit') AS t(tag)
WHERE id = 1;
Interactive Tools for This Topic
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.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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Name the tables involved in this file.
- The references are `import_rows`, `string_to_table`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.