SQL ARRAY_TO_STRING function
Joins the elements of an array column into a single string with your separator, the array counterpart of STRING_AGG over rows.
- Catégorie
- Strings
- Returns
string- In this category
- 23 of 172
Syntaxe
ARRAY_TO_STRING(array, separator [, null_string])
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Not built in | No built-in equivalent. |
| PostgreSQL | Oui | arrays are a PostgreSQL type; other engines have no array columns |
| MySQL | Not built in | No built-in equivalent. |
| SQLite | Not built in | No built-in equivalent. |
| Oracle | Not built in | No built-in equivalent. |
Exemples
PostgreSQL
SELECT array_to_string(ARRAY['a', NULL, 'c'], ',') AS flat; -- a,c
PostgreSQL
SELECT array_to_string(ARRAY[1, NULL, 3], ',', '*') AS flat; -- 1,*,3
PostgreSQL
SELECT string_to_array('a,b,c', ',') AS back; -- {a,b,c}
Bon à savoir
- NULL elements are skipped by default; pass a third argument to render them: array_to_string(a, ',', '*') prints * where the array held NULL.
- An empty array produces an empty string, not NULL. Guard downstream parsing.
- The reverse is string_to_array('a,b', ','), with a third argument for NULL placeholders.
- To aggregate rows instead of array elements, use STRING_AGG; to aggregate across a group from an array, unnest first.
Questions about ARRAY_TO_STRING
How does array_to_string handle NULLs?
It drops them, giving no separator gap. Supply a third argument to print a placeholder for each NULL instead.
Is there an array_to_string in MySQL or SQL Server?
No. Neither has array columns. The row-based equivalents are GROUP_CONCAT and STRING_AGG, which fold rows rather than array elements.
How do I split a string back into an array?
string_to_array('a,b', ',') in PostgreSQL. Note it cannot tell apart an empty element from a NULL unless you pass the third argument consistently.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: PostgreSQL.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.