Arrays and seriesPostgreSQL only

ARRAY_TO_STRING

Joins the elements of an array into one string with a separator.

Syntax

ARRAY_TO_STRING(<array>, <separator>)
ARRAY_TO_STRING(<array>, <separator>, <null replacement>)

The opposite of STRING_TO_ARRAY: it turns an array into text. By default it skips NULL elements, and the third argument sets what to replace them with. Similar to STRING_AGG, but it works with a ready-made array in a single row rather than collecting values from many rows.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

An array into a string
SELECT ARRAY_TO_STRING(ARRAY['sql', 'postgres', 'database'], ', ') AS tags;
tags
sql, postgres, database
NULL: skip or replace
SELECT ARRAY_TO_STRING(ARRAY['Emma', NULL, 'Liam'], ', ') AS skipped,
ARRAY_TO_STRING(ARRAY['Emma', NULL, 'Liam'], ', ', '—') AS replaced;
skippedreplaced
Emma, LiamEmma, —, Liam
Each department's phone numbers
SELECT department,
ARRAY_TO_STRING(ARRAY_AGG(phone ORDER BY name), '; ', 'no phone') AS phones
FROM employees
GROUP BY department
ORDER BY department;
departmentphones
backend+44 7700 900123; no phone
designno phone
frontend+44 7700 900789; +44 7700 900456

STRING_AGG would silently skip people without a phone, but here you can see that someone has none.

Watch out

NULL elements silently disappear, along with any trace that a value was missing. If you need to see the gaps, pass the third argument.

The separator is required: ARRAY_TO_STRING(ARRAY['a']) throws function array_to_string(text[]) does not exist. For no separator — ARRAY_TO_STRING(<array>, '').