How to Split a String by a Delimiter in SQL Server
In this article
In SQL Server, splitting a string by a delimiter (like a comma, semicolon, or pipe) is a common task when you need to break a delimited list into individual rows or values. This guide shows you the most practical methods, from the built-in STRING_SPLIT function (SQL Server 2016 and later) to older alternatives like recursive CTEs and XML. You'll learn how to write the queries, handle edge cases, and avoid common pitfalls.
What You'll Need
- SQL Server 2016 or later for the
STRING_SPLITfunction (recommended). If you're on an older version, you'll need to use the XML or recursive CTE method. - A SQL query editor (SSMS, Azure Data Studio, or any client) connected to your database.
- A table or variable containing the delimited strings you want to split.
Step-by-Step
-
Identify your delimiter and your data source.
Decide what character separates your values (e.g., comma, semicolon, pipe) and where the string lives (a column in a table, a variable, or a literal). For this example, we'll use a comma as the delimiter and a table calledOrderswith a columnItemListcontaining values like'apple,banana,cherry'. -
Use the STRING_SPLIT function (SQL Server 2016+).
The simplest method is the built-inSTRING_SPLITfunction. It takes two arguments: the input string and the delimiter. It returns a single column namedvaluewith each item as a row.
This returns three rows: 'apple', 'banana', 'cherry'.SELECT value FROM STRING_SPLIT('apple,banana,cherry', ','); -
Split a column from a table.
To split values from every row in a table, useCROSS APPLYto join the function to each row:
This gives you one row per item, with the correspondingSELECT o.OrderId, s.value AS Item FROM Orders o CROSS APPLY STRING_SPLIT(o.ItemList, ',') s;OrderId. -
If you need the ordinal position of each item (SQL Server 2022+).
TheSTRING_SPLITfunction added an optional third parameterenable_ordinalin SQL Server 2022. Set it to 1 to get a second columnordinalthat shows the position (1-based):
This returns: (apple, 1), (banana, 2), (cherry, 3).SELECT value, ordinal FROM STRING_SPLIT('apple,banana,cherry', ',', 1); -
If you're on an older version (pre-2016), use a recursive CTE.
For SQL Server 2008–2014, you can split with a recursive common table expression. This method walks through the string, extracting one item at a time:
This works but is more complex. For most cases, upgrading or using the XML method (below) is easier.WITH SplitCTE AS ( SELECT CAST('apple,banana,cherry' AS NVARCHAR(MAX)) AS String, CHARINDEX(',', 'apple,banana,cherry') AS Pos UNION ALL SELECT CAST(SUBSTRING(String, Pos + 1, LEN(String)) AS NVARCHAR(MAX)), CHARINDEX(',', SUBSTRING(String, Pos + 1, LEN(String))) FROM SplitCTE WHERE Pos > 0 ) SELECT CASE WHEN Pos > 0 THEN LEFT(String, Pos - 1) ELSE String END AS Item FROM SplitCTE; -
Alternative for older versions: Use XML.
You can convert the string to XML and then query the nodes. This works on any SQL Server version that supports XML (2005+):
To generate the XML from your string, replace the commas withDECLARE @xml AS XML = '<root><item>apple</item><item>banana</item><item>cherry</item></root>'; SELECT t.value('.', 'VARCHAR(100)') AS Item FROM @xml.nodes('/root/item') AS x(t);</item><item>tags. This method requires careful handling of special characters. -
Handle empty values and trailing delimiters.
STRING_SPLITignores empty values by default. If you need to preserve them (e.g., 'apple,,cherry' should yield an empty string between apples and cherries), you'll need a custom splitter or use the XML method with a different approach. For most business cases, ignoring empties is fine.
Common Mistakes
- Using STRING_SPLIT on SQL Server 2014 or earlier. The function doesn't exist there, so you'll get an error. Use the recursive CTE or XML method instead.
- Assuming the output column is named 'item' or 'value'. In
STRING_SPLIT, the column is always namedvalue. If you alias it, you must use that alias in your SELECT. - Forgetting that STRING_SPLIT returns rows, not a single string. If you need to recombine or pivot, you'll need to use other functions like
STRING_AGG(2017+) or a pivot. - Using the wrong delimiter. If your data uses a pipe or tab, make sure you pass the correct character. A common mistake is using a comma when the data uses a semicolon.
- Not handling NULL values. If the input string is NULL,
STRING_SPLITreturns no rows. You may need to useISNULLor a default value.
Tips
- Use CROSS APPLY for table columns. This is the standard pattern and works efficiently with
STRING_SPLIT. - Check your SQL Server version. Run
SELECT @@VERSIONto see what you're working with. If you're on 2016 or later, you're good to go. - For performance, avoid splitting in a WHERE clause. If you need to filter on a split value, consider storing the data in normalized form instead of splitting on the fly.
- Use the ordinal parameter (2022+) when order matters. Without it, the order of rows is not guaranteed. If you need to know the position, use the ordinal.
- Escape special characters in the XML method. If your data contains
&,<, or>, you must escape them before building the XML.
Troubleshooting
- "Invalid object name 'STRING_SPLIT'" – This means your SQL Server version is older than 2016. Use the recursive CTE or XML method instead. You can also check the compatibility level of your database:
SELECT compatibility_level FROM sys.databases WHERE name = 'YourDB'. It should be 130 or higher for STRING_SPLIT. - Output column not found – If you wrote
SELECT item FROM STRING_SPLIT(...)and get an error, remember the column is namedvalue. UseSELECT valueor alias it:SELECT value AS item. - Empty results when you expect data – Check if the input string is NULL. If so,
STRING_SPLITreturns nothing. UseISNULL(YourColumn, '')before passing it. - Order of rows is unpredictable – Without the ordinal parameter,
STRING_SPLITdoes not guarantee order. If order matters, upgrade to SQL Server 2022 or use a custom splitter that includes an index. - Special characters in XML method – If you get XML parsing errors, you likely have unescaped characters. Use
REPLACEto escape&,<, and>before converting to XML.
Frequently Asked Questions
- Can I split a string into multiple columns instead of rows? Yes, you can use
PARSENAMEfor up to 4 parts (e.g.,PARSENAME('a.b.c.d', 2)returns 'c'), but it's limited and uses dot as delimiter. For more parts, consider usingSTRING_SPLITwith a pivot or use a custom function. - How do I split by a tab character? Pass a tab as the delimiter:
STRING_SPLIT(YourString, CHAR(9)). TheCHAR(9)represents a tab. - Does STRING_SPLIT handle quoted delimiters? No, it does not. It treats every occurrence of the delimiter as a split point, even if it's inside quotes. For CSV with quoted fields, you'll need a more advanced parser.
- Can I use STRING_SPLIT with a variable? Yes, you can pass any string expression, including a variable:
DECLARE @list NVARCHAR(MAX) = 'a,b,c'; SELECT value FROM STRING_SPLIT(@list, ','); - Is there a way to get the count of items? Yes, simply count the rows returned:
SELECT COUNT(*) FROM STRING_SPLIT('a,b,c', ',');This returns 3. - What if my delimiter is a multi-character string?
STRING_SPLITonly accepts a single character. For multi-character delimiters, you'll need to useREPLACEto convert it to a single character first, or use a custom splitter.