SQL STRING_TO_ARRAY function
Splits a string on a separator and returns the elements as a text array.
- 類別
- Strings
- Returns
text[]- In this category
- 106 of 172
語法
string_to_array(string, separator [, null_string])
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | Not built in | No arrays; STRING_SPLIT returns rows instead. |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | Not built in | No array type; SUBSTRING_INDEX or JSON functions. |
| SQLite | Not built in | No array type; JSON arrays via the json functions. |
| Oracle | Not built in | No direct equivalent; collections or REGEXP_SUBSTR walks. |
範例
PostgreSQL
SELECT string_to_array('a,b,c', ',') AS parts; -- {a,b,c}
PostgreSQL
SELECT unnest(string_to_array(tags, ',')) AS tag FROM posts;
小知識
- A NULL separator splits into single characters: string_to_array('abc', NULL) is {a,b,c}. An empty-string separator does the opposite and returns the whole input as one element.
- The optional third argument turns matching elements into NULL: string_to_array('a,,b', ',', '') is {a,NULL,b}.
- Consume the result with unnest (to rows), a 1-based subscript (parts[1]), or array_length for the element count. string_to_table, from PostgreSQL 14, skips the array.
Questions about STRING_TO_ARRAY
How do I turn the array back into rows?
Wrap it with unnest: SELECT unnest(string_to_array(str, ',')). On PostgreSQL 14+ string_to_table(str, ',') does both steps.
Why do empty elements appear in my array?
Adjacent separators create empty-string elements by design. Pass '' as the third argument to turn them into NULL, or filter them out after unnest.
Are array indexes 1-based?
Yes in PostgreSQL: parts[1] is the first element, and parts[0] is NULL rather than an error.
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.