The STRING_SPLIT function in SQL Server splits a string into rows based on a separator, with the syntax STRING_SPLIT ( string , separator ). It returns a single-column table named value containing the substrings, and it is available from SQL Server 2016 onward.
Background and Purpose
Before SQL Server 2016, splitting a comma-separated list into individual rows required complex workarounds: recursive common table expressions (CTEs), XML-based splitting, or custom user-defined functions. These methods were slow, hard to read, and often error-prone. STRING_SPLIT was introduced to provide a built-in, set-based way to perform this common task. It is part of the database engine and requires no additional setup. The function is designed to be used in a FROM clause, just like a table or a view, and it works with any string data type (though the input must be nvarchar, varchar, nchar, or char).
Basic Syntax and Usage
The syntax is straightforward:
STRING_SPLIT ( string , separator )
Here, string is the expression to split, and separator is a single-character expression that marks the boundaries. The function returns a table with one column named value. For example, to split the string ‘apple,banana,cherry’ by comma:
SELECT value FROM STRING_SPLIT('apple,banana,cherry', ',');
This returns three rows: ‘apple’, ‘banana’, and ‘cherry’. You can use the result in any context where a table is allowed, such as joining, filtering, or inserting into another table. Note that the output column is always named value; you can alias it if needed: SELECT value AS fruit FROM STRING_SPLIT(...).
Practical Examples
Consider a table Orders with a column ProductIDs containing comma-separated numbers. To join with a Products table:
SELECT p.ProductName
FROM Orders o
CROSS APPLY STRING_SPLIT(o.ProductIDs, ',') AS sp
JOIN Products p ON p.ProductID = CAST(sp.value AS INT);
Here CROSS APPLY applies the split per row. You can also filter using WHERE on the split result, or use it to check membership: WHERE 'apple' IN (SELECT value FROM STRING_SPLIT(@list, ',')). For a dynamic IN clause, you can pass a comma-separated list to a stored procedure and use STRING_SPLIT to filter.
Choosing the Right Separator
The separator must be a single character (of type nvarchar or varchar with length 1). It can be any character, including spaces, semicolons, pipes, or even newline characters. If you need multi-character delimiters like ‘||’, STRING_SPLIT does not support them directly; you would need to replace them with a single character first (e.g., REPLACE(@string, '||', '|')) or use a different method. Also, the separator is case-sensitive in most collations, so ‘,’ and ‘,’ are the same, but ‘A’ and ‘a’ are different if the collation is case-sensitive. Be mindful of trailing or leading empty strings: STRING_SPLIT does not return empty substrings. For example, splitting ‘a,,b’ returns ‘a’ and ‘b’ only, skipping the empty middle element. If you need to preserve empty values, you must use a different approach, such as a custom splitter or XML.
Common Problems and Misconceptions
One common misconception is that STRING_SPLIT returns an ordinal position column. It does not. The output order is not guaranteed; it is generally the order of the substrings, but you should not rely on it. If you need the position, you must use a different function or add a row_number with a stable ordering, which is not possible without an ordinal. Another issue is that the input string cannot be of type text or ntext; those deprecated types are not supported. Also, the separator must be a single character; if you pass a multi-character string, you get an error. Finally, STRING_SPLIT is not available in Azure SQL Data Warehouse or Parallel Data Warehouse; it is only in SQL Server 2016+ and Azure SQL Database. For older versions, you need alternative solutions.
Performance and Best Practices
When used correctly, STRING_SPLIT is efficient because it is implemented as a table-valued function that streams rows. However, performance can degrade if you split large strings or call it many times in a loop. To optimize, avoid splitting inside a scalar UDF or a cursor; instead, use CROSS APPLY to join with the base table. Also, consider the collation: if you are splitting strings with different collations, you may need to specify collation explicitly to avoid errors. For very large strings (over 8,000 bytes for varchar, 4,000 for nvarchar), you must use varchar(max) or nvarchar(max); the function supports these. A common best practice is to use STRING_SPLIT for one-time splits, but for repeated splitting of the same list, consider storing the split results in a table or using a JSON array with OPENJSON if you are on a newer version.
Alternatives and Comparisons
Other methods for splitting strings include:
XMLmethod:SELECT value FROM (SELECT CAST('<x>' + REPLACE(@string, ',', '</x><x>') + '</x>' AS XML) AS x) AS t CROSS APPLY x.nodes('/x') AS n(value)– works in older versions but is slower and has XML escaping issues.- Recursive CTE: uses
CHARINDEXto loop, but is verbose and often slower. - Custom CLR function: can be fast but requires enabling CLR and deploying assemblies.
OPENJSON(SQL Server 2016+): if you convert the string to a JSON array (e.g.,SELECT value FROM OPENJSON('[' + @json + ']')), it returns avaluecolumn and also an ordinalkey, which is useful. However, it requires the string to be valid JSON, so you must format it accordingly.
Compared to these, STRING_SPLIT is the simplest and most readable, but it lacks the ordinal position that OPENJSON provides. Choose STRING_SPLIT for simple splits where order is not important, and OPENJSON when you need the position or are already working with JSON.
Frequently Asked Questions
Does STRING_SPLIT return an ordinal position column?
No. In the original implementation, STRING_SPLIT returns only the value column. Microsoft added an optional ordinal column in SQL Server 2022 and Azure SQL Database, but only if you use the enable_ordinal parameter: STRING_SPLIT('a,b,c', ',', 1) returns both value and ordinal. For earlier versions, you must use a different method if you need the position.
Can I use STRING_SPLIT with a multi-character delimiter?
No, the separator must be a single character. If you have a multi-character delimiter, you can work around it by first replacing it with a single character that does not appear in the string, then splitting. For example, REPLACE(@string, '||', '|') then split by ‘|’. Be careful to choose a placeholder that is not in the original data.
Why does STRING_SPLIT skip empty values?
By design, STRING_SPLIT does not return empty substrings. For instance, splitting ‘a,,b’ returns ‘a’ and ‘b’ only. If you need to preserve empty strings, you must use a custom splitter that includes them, or use OPENJSON with a properly formatted JSON array that includes empty strings.
Is STRING_SPLIT available in all SQL Server editions?
Yes, STRING_SPLIT is available in all editions of SQL Server 2016 and later, including Express and LocalDB. However, it is not available in SQL Server 2014 or earlier. For Azure SQL Database, it is available. For Azure Synapse Analytics, it is not available; use a different method there.
What is the difference between STRING_SPLIT and OPENJSON for splitting?
OPENJSON is designed for JSON, but can split strings if you convert them to a JSON array. It returns a value column and a key column (which is the ordinal position). STRING_SPLIT is simpler and faster for basic splits, but lacks the ordinal. If you need the position, use OPENJSON (or STRING_SPLIT with the ordinal parameter in SQL 2022+).
Can I use STRING_SPLIT to split a column in a SELECT without CROSS APPLY?
No, because STRING_SPLIT is a table-valued function, you must use CROSS APPLY (or OUTER APPLY) to call it for each row in a query. You cannot call it directly in the SELECT list. For example: SELECT o.OrderID, sp.value FROM Orders o CROSS APPLY STRING_SPLIT(o.Items, ',') sp.
Related
- Google Sheets Percentage Format: How to Use It
- How to Generate Random Numbers on a Calculator
- Maximum Data Entry: Definition, Limits, and Real Usage
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Can You Custom Freeze Panes in Excel? Here’s HowYes. In Excel for Microsoft 365 on Windows, select the cell immediately below the rows and to the…
- State Heat Map in Excel: Create, Format, and TroubleshootTo make a U.S. state heat map in Excel for Microsoft 365 on Windows, put each state and…
- Add Page Numbers in Word Using a Keyboard ShortcutIn Word for Microsoft 365 on Windows, press Alt+N to open the Insert tab, then follow the on-screen…
- Excel Truck Group Jobs: Pay, Hiring & ReviewsExcel Truck Group jobs include full-time positions as diesel technicians, parts specialists, service advisors, and Class A CDL…
- Excel Certifications: The Current Options ExplainedThe main Microsoft Excel certifications are Microsoft Office Specialist (MOS) Excel Associate for Microsoft 365 Apps (exam MO-210)…
- Excel Text to Columns: How to Split DataTo change text to columns in Excel for Microsoft 365 on Windows, select the cells, then choose Data…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.