Sub topic 14
Converting arrays and delimited strings
This chapter assumes you know the cast syntaxes (CAST, ::, typed literals) and the difference between implicit, assignment and explicit casts from earlier chapters. It also assumes you know that a cast from text to another type calls that type's input function. Here you apply those ideas to arrays, and to strings that hold lists of values, such as '1,2,3'.
Two kinds of "list in a string"
A list stored in text comes in one of two shapes, and PostgreSQL handles them differently.
- Array literal text, such as
{1,2,3}. PostgreSQL's own array syntax. A cast parses it directly. - Delimited text, such as
1,2,3orred;green;blue. This has no special meaning to PostgreSQL. You split it with a function first, then cast the pieces.
Casting array literals
An array literal is parsed by the array input function. That function parses the text, then runs the element type's input function on each element.
SELECT '{1,2,3}'::int[] AS ints,
'{a,b,c}'::text[] AS words,
'{1,NULL,3}'::int[] AS with_null,
'{{1,2},{3,4}}'::int[] AS matrix,
'{"a,b",c}'::text[] AS quoted;The last column has two elements, a,b and c, because double quotes protect the comma. Three rules cover most surprises:
- An unquoted
NULLis a SQL null. The quoted"NULL"is the four-letter string. - An empty string element must be written
"". Bare nothing between commas is a syntax error. - Whitespace around an element is ignored for numbers, so
'{1, 2, 3}'::int[]works.
The ARRAY[1,2,3] constructor is not a cast. It builds an array from expressions and infers the element type from them, using the resolution rules covered in the chapter on UNION and CASE.
Splitting delimited strings
string_to_array(text, delimiter) returns text[]. Add a cast to get typed elements.
SELECT string_to_array('1,2,3', ',') AS as_text,
string_to_array('1,2,3', ',')::int[] AS as_int,
string_to_array('', ',') AS empty_input,
string_to_array(NULL, ',') AS null_input,
string_to_array('abc', '') AS no_split,
string_to_array('abc', NULL) AS per_char,
string_to_array('a,,c', ',', '') AS null_marker;The edge cases:
- An empty input string gives an empty array
{}, not an array holding one empty string. - A null input gives null.
- An empty delimiter keeps the whole string as one element. A null delimiter splits into single characters.
- The optional third argument names a string that becomes a SQL null. With
''above, the middle element ofa,,cbecomesNULL.
For inputs with mixed or variable separators, use regexp_split_to_array:
SELECT regexp_split_to_array('1, 2;3 4', '[,;\s]+')::int[] AS ints;The reverse direction is array_to_string(array, delimiter [, null_string]). By default it silently drops null elements.
SELECT array_to_string(ARRAY[1,NULL,3], ',') AS dropped,
array_to_string(ARRAY[1,NULL,3], ',', 'NULL') AS kept,
array_to_string('{{1,2},{3,4}}'::int[], ',') AS flattened;The results are 1,3, 1,NULL,3 and 1,2,3,4. Multidimensional arrays are flattened, so the output cannot be turned back into the original shape.
Casting between array types
text[]::int[] works element by element. PostgreSQL does not list array-to-array casts in pg_cast. When no entry exists for a pair of array types, it checks whether their element types have a cast. If they do, it applies that cast to each element, in the same context (implicit, assignment or explicit) the element cast is allowed in.
SELECT ARRAY['1','2','3']::int[] AS text_to_int,
ARRAY[1,2,3]::bigint[] AS widened,
ARRAY[1.7, 2.2]::int[] AS rounded,
ARRAY[1,2,3]::text[] AS to_text;The numeric rules apply per element, so 1.7 becomes 2. A failure in any element fails the whole conversion:
SELECT string_to_array('1,x,3', ',')::int[];
-- ERROR: invalid input syntax for type integer: "x"The error names the bad element but not its position. Casting an array to a single text value gives the literal form, not a delimited string:
SELECT ARRAY[1,2,3]::text AS literal_form,
array_to_string(ARRAY[1,2,3], ',') AS delimited_form;This returns {1,2,3} and 1,2,3. Choose the one your consumer expects.
Turning delimited columns into rows and back
Legacy schemas often store lists in one text column. Combine string_to_array, unnest and a cast to work with them as rows.
CREATE TABLE orders (id integer PRIMARY KEY, item_ids text);
INSERT INTO orders VALUES (1, '10,20,30'), (2, '20'), (3, '');
SELECT o.id, i.item_id::int AS item_id
FROM orders AS o
CROSS JOIN LATERAL unnest(string_to_array(o.item_ids, ',')) AS i(item_id);Order 3 produces no rows because its array is empty. A plain unnest in the select list behaves the same way. To go the other way, aggregate with array_agg(item_id ORDER BY item_id) or string_agg(item_id::text, ',' ORDER BY item_id).
Handling bad elements safely
On PostgreSQL 16 and later, pg_input_is_valid tests text against a type without raising an error. It accepts array types, so it can validate a whole array literal. Delimited strings have to be checked per element.
SELECT pg_input_is_valid('{1,2,3}', 'integer[]') AS good_literal,
pg_input_is_valid('{1,x,3}', 'integer[]') AS bad_literal;
SELECT array_agg(t.v::int ORDER BY t.ord) AS cleaned
FROM unnest(string_to_array('10;20;x;30', ';')) WITH ORDINALITY AS t(v, ord)
WHERE pg_input_is_valid(t.v, 'integer');The second query returns {10,20,30} and discards x. Decide deliberately whether dropping bad input is right. Often the better choice is to reject the whole value.
Passing a list as one parameter
A common application pattern sends one text parameter, such as '1,2,3', and compares a column to it.
SELECT * FROM orders
WHERE id = ANY (string_to_array('1,2', ',')::int[]);The cast happens on the parameter side, so the integer primary key index stays usable. The opposite form, id::text = ANY (string_to_array('1,2', ',')), casts the column and prevents a plain index on id from being used. A literal such as id = ANY ('{1,2}') also works, because the untyped literal is resolved as integer[].
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `malformed array literal` | Delimited text such as `1,2,3` cast directly with `::int[]` | Use `string_to_array`, or wrap the text in braces |
| `invalid input syntax for type integer` | One bad element in the list | Filter with `pg_input_is_valid` or clean the data |
| Missing nulls in output | `array_to_string` drops nulls by default | Pass the third argument |
| `{}` expected, one empty element seen | Confusing `''` input with `{""}` | Remember empty input gives an empty array |
Exercise
What does arraytostring(ARRAY[1,NULL,3], ',') return, and how do you make the null appear as the word NULL in the output?
Show answer
It returns '1,3', because null elements are skipped by default. Pass a third argument: arraytostring(ARRAY[1,NULL,3], ',', 'NULL') returns '1,NULL,3'.
Exercise
Given the string '5, 6;x;7', write a query for PostgreSQL 16 or later that returns the valid integers as an int[] in their original order. Split on the semicolon only.
Show answer
SELECT arrayagg(t.v::int ORDER BY t.ord) FROM unnest(stringtoarray('5, 6;x;7', ';')) WITH ORDINALITY AS t(v, ord) WHERE pginputisvalid(t.v, 'integer'); The pieces are '5, 6', 'x' and '7'. The first is not a valid integer because of the comma, so only {7} is returned. To keep 5 and 6 you would split on a regular expression with regexpsplitto_array.