Sub topic 11
Splitting strings and aggregating rows into text
This chapter covers the functions that move data between three shapes: one delimited string, an array of pieces, and a set of rows. It assumes you can write SELECT, WHERE and GROUP BY queries, know that NULL means "unknown", and can run queries in psql or another client. Some examples use arrays and unnest, which are explained as they appear.
The three shapes of text data
A comma-separated value such as 'sql,postgres,text' can be handled in three forms:
- A single
textvalue. - A
text[]array, with one element per piece. - A set of rows, with one row per piece.
Each function in this chapter converts from one form to another.
Taking one piece with split_part
split_part(string, delimiter, n) returns the nth piece, counting from 1. It is the quickest way to pull a single field out of a string.
SELECT split_part('[email protected]', '@', 2) AS domain,
split_part('a/b/c/d', '/', -1) AS last_piece,
split_part('a,b,c', ',', 5) AS out_of_range;| domain | last_piece | out_of_range |
|---|---|---|
| example.com | d | (empty string) |
Three behaviors matter here:
- A position past the last piece returns an empty string, not
NULLand not an error. You cannot tell "missing piece" from "empty piece" without checking the data. - A negative position counts from the end. This works in PostgreSQL 14 and later. Older versions raise an error.
- Position
0always raises an error:field position must not be zero.
The delimiter is a literal string, not a pattern. split_part(x, '.', 2) splits on a period, not on "any character".
Splitting into an array
string_to_array(string, delimiter [, null_string]) returns a text[].
SELECT string_to_array('a,b,c', ',') AS items,
string_to_array('a,,c', ',') AS with_empty,
string_to_array('abc', NULL) AS characters,
string_to_array('', ',') AS empty_input,
string_to_array('a,N/A,c', ',', 'N/A') AS with_null;The results are:
| Column | Value |
|---|---|
| items | `{a,b,c}` |
| with_empty | `{a,"",c}` |
| characters | `{a,b,c}` |
| empty_input | `{}` |
| with_null | `{a,NULL,c}` |
- Empty pieces are kept. Two adjacent delimiters produce an empty string element.
- A
NULLdelimiter splits into single characters. An empty-string delimiter does not.string_to_array('abc', '')returns{abc}. - An empty input gives an empty array, not an array holding one empty string.
- The optional third argument turns a marker into a real
NULL. This is useful for imported data whereN/Aor\Nmeans missing.
Arrays are indexed from 1, so (string_to_array('a,b,c', ','))[2] returns b. The parentheses are required around the function call before subscripting.
Splitting into rows
To get one row per piece, expand the array with unnest. Add WITH ORDINALITY if you need each piece's position.
SELECT t.item, t.pos
FROM unnest(string_to_array('sql,postgres,text', ',')) WITH ORDINALITY AS t(item, pos);This returns sql | 1, postgres | 2 and text | 3.
PostgreSQL 14 added string_to_table, which skips the intermediate array:
SELECT string_to_table('sql,postgres,text', ',') AS item;string_to_table does not return positions. If order matters, use unnest ... WITH ORDINALITY.
Splitting on a pattern
When the separator varies, use the regular-expression versions. Their second argument is a POSIX pattern.
SELECT regexp_split_to_array('one two three', '\s+') AS words,
regexp_split_to_table('a1b22c', '\d+') AS pieces;The first column is {one,two,three}. The second produces the rows a, b and c. Because the pattern \s+ matches runs of whitespace, repeated spaces do not create empty pieces. Pattern splitting costs more than literal splitting. Use string_to_array when the delimiter is a fixed string.
Splitting stored columns
A column that holds a delimited list breaks first normal form. It is still common in imported data. A lateral expansion lets you query it:
WITH posts(id, tags) AS (
VALUES (1, 'sql,postgres,text'),
(2, 'postgres'),
(3, NULL)
)
SELECT p.id, t.tag
FROM posts AS p
CROSS JOIN LATERAL unnest(string_to_array(p.tags, ',')) AS t(tag)
ORDER BY p.id, t.tag;Post 1 yields three rows and post 2 yields one. Post 3 yields none, because string_to_array(NULL, ',') returns NULL and unnest(NULL) returns zero rows. If you need every post to appear, use LEFT JOIN LATERAL ... ON true.
Joining an array with array_to_string
array_to_string(array, delimiter [, null_string]) is the reverse of string_to_array.
SELECT array_to_string(ARRAY['a', NULL, 'c'], '-') AS skipped,
array_to_string(ARRAY['a', NULL, 'c'], '-', '?') AS replaced;This returns a-c and a-?-c. By default, NULL elements are left out together with their separator. Pass a third argument to keep a placeholder instead. This differs from the || operator, which returns NULL when any operand is NULL.
Aggregating rows into one string with string_agg
string_agg(expression, delimiter) is an aggregate function. It collapses the rows of each group into a single string.
WITH employees(name, department) AS (
VALUES ('Ana', 'Sales'),
('Raj', 'Sales'),
('Mei', 'IT'),
('Zed', NULL)
)
SELECT department,
string_agg(name, ', ' ORDER BY name) AS members
FROM employees
GROUP BY department
ORDER BY department;The output is:
| department | members |
|---|---|
| IT | Mei |
| Sales | Ana, Raj |
| (null) | Zed |
Always order inside the call
Without an ORDER BY inside the parentheses, the concatenation order is whatever order the rows reach the aggregate. That order can change between runs, after an index is added, or when the planner picks a different plan. An outer ORDER BY on the query does not fix it, because it sorts the output rows, not the rows fed into the aggregate. Write string_agg(name, ', ' ORDER BY name) whenever the order matters.
NULL handling and empty groups
string_aggignoresNULLinput values. The delimiter is added only between non-null values, so you never get a dangling,.- If every value in a group is
NULL, or the group has no rows, the result isNULL, not an empty string. Wrap it ascoalesce(string_agg(...), '')when you need text. - The expression must be
text(orbytea). Cast other types explicitly, for examplestring_agg(id::text, ',').
DISTINCT and FILTER
DISTINCT removes duplicate values before joining. When you combine it with ORDER BY, the sort expression must match the aggregated expression. FILTER restricts which rows contribute.
WITH orders(customer, status, product) AS (
VALUES ('Ana', 'shipped', 'pen'),
('Ana', 'shipped', 'pen'),
('Ana', 'shipped', 'ink'),
('Ana', 'cancelled', 'desk')
)
SELECT customer,
string_agg(DISTINCT product, ', ' ORDER BY product)
FILTER (WHERE status = 'shipped') AS shipped_products
FROM orders
GROUP BY customer;This returns ink, pen for Ana. The duplicate pen is removed and the cancelled desk is excluded.
A split-and-rejoin round trip
You can combine the pieces to rebuild a string after transforming each part. This example capitalizes each word of a hyphenated slug:
SELECT string_agg(initcap(t.word), ' ' ORDER BY t.pos) AS title
FROM unnest(string_to_array('sql-string-functions', '-'))
WITH ORDINALITY AS t(word, pos);The result is Sql String Functions. The pos column from WITH ORDINALITY keeps the original word order.
Choosing between the functions
| You want | Use |
|---|---|
| One field from a fixed-delimiter string | `split_part` |
| An array of all pieces | `string_to_array` |
| One row per piece | `unnest(string_to_array(...))` or `string_to_table` |
| Split on a varying separator | `regexp_split_to_array` or `regexp_split_to_table` |
| Join array elements | `array_to_string` |
| Join values from many rows | `string_agg` |
| Collect rows into an array, keeping `NULL`s | `array_agg` |
Common mistakes
- Using
split_partand trusting an empty result. An empty string can mean a missing piece or a genuinely empty one. - Omitting
ORDER BYinstring_agg. The output looks fine in testing and changes later. - Expecting an empty string from an empty group. You get
NULL. - Forgetting the lateral join drops
NULLcolumns. Rows whose list isNULLdisappear from the result. - Aggregating non-text columns without a cast.
string_agg(id, ',')fails with a function-does-not-exist error for an integerid.
Exercise
Given the table visits(user_id int, page text), write a query that returns one row per user with a single string of that user's distinct pages, sorted alphabetically and separated by > . Users with no non-null pages should show an empty string instead of NULL.
Show answer
SELECT userid, coalesce(stringagg(DISTINCT page, ' > ' ORDER BY page), '') AS pages FROM visits GROUP BY userid; DISTINCT removes repeated pages. The ORDER BY inside the call must use the same expression (page) and gives a stable order. stringagg ignores NULL pages and returns NULL when none remain, so coalesce converts that to an empty string.
Exercise
What do splitpart('a,b,c', ',', 4) and stringto_array('', ',') return, and how do they differ from what you might expect?
Show answer
splitpart returns an empty string (not NULL and not an error) because position 4 is past the last piece. stringto_array('', ',') returns the empty array {}, not an array containing one empty string. In both cases the function handles the missing data quietly, so you need to check for it explicitly if it matters.