To split a string in SQL Server, the best method is to use the built-in STRING_SPLIT function (available since SQL Server 2016), which returns a single column of substrings. For example, SELECT value FROM STRING_SPLIT('apple,banana,cherry', ',') returns three rows. If you need the ordinal position of each element, use the OPENJSON function or a custom user-defined function, as STRING_SPLIT does not guarantee order or provide an index.
Why String Splitting Is Needed
Relational databases are designed to store data in separate columns and rows, not in delimited lists. However, legacy systems, imported data, or user input often contain comma-separated values (CSV) inside a single column. Splitting such strings is a common requirement for reporting, data cleaning, or joining with other tables. For instance, you might have a table with a column like tags containing ‘red,green,blue’ and need to normalize it into rows for a many-to-many relationship.
Using STRING_SPLIT (SQL Server 2016+)
STRING_SPLIT is the simplest and most efficient built-in way. Its syntax is:
STRING_SPLIT ( string , separator )
It returns a table with a single column named value. Example:
SELECT value FROM STRING_SPLIT('one,two,three', ',');
Output:
value
-----
one
two
three
Important limitations:
- It does not return an ordinal (position) column, and the order of rows is not guaranteed.
- It only accepts a single-character separator (e.g., comma, semicolon, pipe). You cannot split on a multi-character delimiter like ‘||’.
- Empty substrings are omitted by default (e.g., ‘a,,b’ yields ‘a’ and ‘b’ only).
Getting Ordinal Positions with OPENJSON
If you need to know the position of each element (e.g., to keep the order or to map to a fixed number of columns), use OPENJSON with a JSON array trick. Convert the delimited string into a JSON array by replacing the separator with a comma and wrapping in brackets, then use OPENJSON to get both key (the index) and value.
DECLARE @str NVARCHAR(100) = 'apple,banana,cherry';
SELECT [key] AS position, [value]
FROM OPENJSON('["' + REPLACE(@str, ',', '","') + '"]');
Output:
position | value
---------+--------
0 | apple
1 | banana
2 | cherry
Note that the index starts at 0. This method works for any separator, but you must escape double quotes if they appear in the data. For most use cases, this is a reliable way to get order.
Using a Custom Split Function (Pre-2016)
If you are on SQL Server 2014 or earlier, or if you need multi-character delimiters, you can create a user-defined function (UDF) that loops through the string using CHARINDEX and SUBSTRING. Here is a common inline table-valued function (iTVF) that returns both position and value:
CREATE FUNCTION dbo.SplitString
(
@string NVARCHAR(MAX),
@delimiter NVARCHAR(10)
)
RETURNS TABLE
AS
RETURN
(
WITH cte AS (
SELECT
CAST(1 AS BIGINT) AS Position,
CAST(1 AS BIGINT) AS StartIdx,
CHARINDEX(@delimiter, @string) AS EndIdx
WHERE @string IS NOT NULL
UNION ALL
SELECT
Position + 1,
EndIdx + LEN(@delimiter),
CHARINDEX(@delimiter, @string, EndIdx + LEN(@delimiter))
FROM cte
WHERE EndIdx > 0
)
SELECT
Position,
SUBSTRING(@string, StartIdx,
CASE WHEN EndIdx > 0 THEN EndIdx - StartIdx ELSE LEN(@string) - StartIdx + 1 END) AS Value
FROM cte
);
Then call it:
SELECT * FROM dbo.SplitString('a;b;c', ';');
This recursive CTE approach is efficient for most strings. Always test with your data volume, as very long strings or many splits can impact performance.
How to Choose the Right Method
Your choice depends on your SQL Server version and requirements:
- SQL Server 2016+ and you only need the values (no order): use
STRING_SPLIT. - SQL Server 2016+ and you need the position: use
OPENJSONtrick. - SQL Server 2014 or older: create a custom function (like the one above) or use a numbers table approach.
- Multi-character delimiter (e.g., ‘||’):
STRING_SPLITwon’t work; useOPENJSON(replace the delimiter with a comma) or a custom function. - Need to handle empty elements (e.g., ‘a,,b’ should return an empty string):
STRING_SPLITomits them; useOPENJSONor a custom function that preserves them.
Common Problems and Misconceptions
A frequent misconception is that STRING_SPLIT returns rows in the same order as the input. It does not guarantee order; you must use OPENJSON or a custom function if order matters. Another issue is performance: using a scalar UDF that loops character-by-character is slow on large tables. Prefer set-based approaches like STRING_SPLIT or the recursive CTE. Also, beware of the value column’s data type: it is nvarchar(max), so you may need to cast it to a specific length when inserting into a column.
Comparison with Other Methods
Besides STRING_SPLIT and OPENJSON, there are older techniques:
- XML method: Convert the string to XML and use
nodes()to shred it. Works in all versions but is slower and has issues with special XML characters. - Numbers table: Join a sequence of numbers to extract substrings using
SUBSTRINGandCHARINDEX. This is fast for large strings but requires a pre-existing numbers table. - While loop: Simple to write but extremely slow on large data sets; avoid for production.
For most modern applications, STRING_SPLIT is the fastest and most readable. OPENJSON is slightly slower but provides more flexibility.
Frequently Asked Questions
Can I split a string by a multi-character delimiter?
Yes, but not with STRING_SPLIT. Use OPENJSON by first replacing the multi-character delimiter with a comma, then converting to a JSON array. Alternatively, write a custom function that uses CHARINDEX with the full delimiter.
Why does STRING_SPLIT not return an ordinal column?
Microsoft designed it that way to allow parallel query execution and to keep the function lightweight. If you need the position, use OPENJSON or a custom function. In SQL Server 2022, there is an optional enable_ordinal parameter that adds a 1-based ordinal column, but it is not available in earlier versions.
How do I split a string into columns, not rows?
If you need a fixed number of columns (e.g., split ‘John,Doe,30’ into three columns), use PARSENAME for up to four parts (replace the delimiter with a dot) or use SUBSTRING with CHARINDEX. For more than four parts, consider using OPENJSON with a pivot or a custom function.
Is STRING_SPLIT faster than a custom function?
Generally yes, because it is implemented in C++ and can run in parallel. However, if you need ordinal positions, OPENJSON is comparable in speed to a well-written inline TVF. Always test with your actual data size.
How do I handle NULL or empty strings?
STRING_SPLIT returns no rows if the input is NULL or empty. If you need to treat an empty string as one empty element, use a custom function or OPENJSON with a conditional. For example, SELECT value FROM STRING_SPLIT('', ',') returns zero rows.
Can I use STRING_SPLIT in a JOIN?
Yes, you can use it in a CROSS APPLY to join each element to another table. Example: SELECT * FROM Products p CROSS APPLY STRING_SPLIT(p.Tags, ',') s.