Sub topic 14
Converting Arrays and Delimited Strings
This chapter assumes you know SELECT, basic casts, and PostgreSQL types such as text and integer. It also assumes access to PostgreSQL through psql or another SQL client.
A PostgreSQL array is one value containing an ordered set of elements. The element type is part of the array type: text[] stores text values, while integer[] stores integers. A delimited string such as '10,20,30' is only text until you convert it.
Creating and converting arrays
Use an array constructor when the elements already have SQL values:
SELECT ARRAY[10, 20, 30] AS numbers,
ARRAY['red', 'green', 'blue'] AS colors;You can also write an array literal as text and cast it to an array type. PostgreSQL uses braces and commas in this format:
SELECT '{1,2,3}'::integer[] AS numbers,
'{"red","green","blue"}'::text[] AS colors;These forms are different from ordinary delimited strings. A string uses the delimiter you choose, while an array literal follows PostgreSQL's array-literal syntax.
Splitting and joining delimited text
string_to_array splits text at a delimiter and returns a text[] value. You can explicitly cast that result to another array type when every element is valid input for the target type.
SELECT string_to_array('1,2,3', ',')::integer[] AS numbers,
array_to_string(ARRAY[1, 2, 3], ',') AS csv;The first expression produces {1,2,3} as an integer[]. The second produces the text value 1,2,3.
For delimiters surrounded by inconsistent whitespace, use a regular expression:
SELECT regexp_split_to_array('1, 2, 3', '\s*,\s*')::integer[] AS numbers;The expression removes whitespace around each comma before converting the elements.
| Input operation | PostgreSQL function | Result |
|---|---|---|
| Split text | `string_to_array(text, delimiter)` | `text[]` |
| Split with a pattern | `regexp_split_to_array(text, pattern)` | `text[]` |
| Join array elements | `array_to_string(array, delimiter)` | `text` |
Expanding arrays into rows
Use unnest when a query needs one row per element. This is useful for filtering, joining, or aggregating array contents.
SELECT element
FROM unnest(ARRAY[10, 20, 30]::integer[]) AS elements(element)
WHERE element >= 20;The result contains 20 and 30.
Empty strings and nulls need attention. string_to_array('', ',') returns an empty array, while a missing input value produces NULL. A delimiter can also be specified as NULL to split into individual characters, although that is rarely the intended data model.
Exercise
What type does string_to_array('4,5,6', ',') return, and how can you convert it to an integer array?
Show answer
It returns text[]. Use string_to_array('4,5,6', ',')::integer[].