// strings reference

SQL STRING_SPLIT function

A table-valued function that splits a string on a single-character separator and returns one row per element.

Catégorie
Strings
Returns
table of value rows
In this category
103 of 172

Syntaxe

STRING_SPLIT(string, separator [, enable_ordinal])
CROSS APPLY STRING_SPLIT(col, ',')

Each block is a separate form. The support table and the examples show which engine takes which.

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Oui Needs database compatibility level 130+; the ordinal argument needs SQL Server 2022 or Azure SQL.
PostgreSQL Different name or syntax string_to_table(str, ',') from PostgreSQL 14, or regexp_split_to_table.
MySQL Not built in No built-in; JSON_TABLE or a recursive CTE fills the gap.
SQLite Not built in No built-in; json_each over a JSON array is the common trick.
Oracle Not built in No STRING_SPLIT; walk the string with REGEXP_SUBSTR and CONNECT BY.

Exemples

SQL Server

SELECT value FROM STRING_SPLIT('a,b,c', ',');

SQL Server

SELECT t.id, s.value AS tag
FROM posts t
CROSS APPLY STRING_SPLIT(t.tags, ',', 1) s
ORDER BY t.id, s.ordinal;

Bon à savoir

  • It returns rows, not an array, so you join it: CROSS APPLY STRING_SPLIT(t.csv, ',') produces one row per element of each source row.
  • Without the third argument row order is not guaranteed. SQL Server 2022 and Azure SQL accept STRING_SPLIT(str, ',', 1), which adds a 1-based ordinal column to sort on.
  • Empty elements survive: 'a,,b' yields three rows, the middle one empty. Filter value <> '' if blanks should vanish. Spaces after the comma are kept too; TRIM the value.

Questions about STRING_SPLIT

How do I keep the original order of the elements?

Pass 1 as the third argument (SQL Server 2022+ and Azure SQL): STRING_SPLIT(str, ',', 1) returns an ordinal column; ORDER BY it. Older versions have no reliable order, so use a JSON array and OPENJSON, whose key column is the position.

What is the PostgreSQL equivalent?

string_to_table(str, ',') from PostgreSQL 14, unnest(string_to_array(str, ',')) in any version, or regexp_split_to_table for regex separators. All return one row per element.

Can STRING_SPLIT split on multi-character separators?

No, the separator must be exactly one character. Replace a multi-character delimiter with a character that never occurs in the data first, then split.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL.

// fewer lookups

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.