Microsoft SQL Split String: Methods and Step-by-Step Guide
In this article
To split a string in Microsoft SQL Server, the most efficient method is using the built-in STRING_SPLIT function, which converts a delimited string into a table of rows. For example, running SELECT value FROM STRING_SPLIT('Red,Blue,Green', ',') will return three separate rows containing 'Red', 'Blue', and 'Green'. This function is available in SQL Server 2016 and later versions. If you are using an older version of SQL Server, you must create a User-Defined Function (UDF) to achieve the same result.
What You'll Need
- Access to a Microsoft SQL Server instance (2016 or newer for the built-in function).
- SQL Server Management Studio (SSMS) or another compatible SQL query editor.
- A string containing a consistent delimiter (such as a comma, pipe, or semicolon).
- The necessary permissions to execute SELECT statements and, if using the legacy method, permissions to create functions in the database.
Step-by-Step
-
Basic Split with a Hardcoded String:
Start by testing the function with a simple string to ensure your SQL Server version supports it. Use the following syntax:
SELECT value FROM STRING_SPLIT('Apple,Banana,Orange', ',');In this example, the first argument is the string you want to break apart, and the second argument is the single-character delimiter. The function returns a table with a single column named "value". -
Splitting a String from a Variable:
In most real-world scenarios, your string will be stored in a variable. Define the variable first, then pass it into the function:
DECLARE @MyList NVARCHAR(MAX) = 'SQL,Python,Java,C#'; SELECT value FROM STRING_SPLIT(@MyList, ',');This allows you to dynamically handle input coming from application parameters or other queries. -
Splitting Columns within a Table (CROSS APPLY):
When you have a table where one column contains delimited lists (a common sign of non-normalized data), you cannot use a simple SELECT. Instead, use the CROSS APPLY operator. This operator joins each row of the main table to the result set returned by the STRING_SPLIT function for that specific row:
SELECT t.UserID, s.value FROM UsersTable t CROSS APPLY STRING_SPLIT(t.Skills, ',');If a user has three skills listed in their "Skills" column, CROSS APPLY will create three separate rows for that user, one for each skill. -
Filtering and Cleaning the Split Results:
Split strings often contain unwanted whitespace (e.g., "Apple, Banana" results in " Banana" with a leading space). Use the TRIM function to clean the output and a WHERE clause to remove empty entries:
SELECT TRIM(value) AS CleanValue FROM STRING_SPLIT('Apple, Banana, , Orange', ',') WHERE value <> '';The TRIM function removes leading and trailing spaces, while the WHERE clause ensures that empty elements (caused by double commas) are not included in your final result set. -
Implementing a Split Function for Older SQL Versions (Pre-2016):
If you are using SQL Server 2014 or earlier, STRING_SPLIT does not exist. You must create a Table-Valued Function. Here is the process:
- Create a new function that accepts a string and a delimiter as parameters.
- Use a WHILE loop combined with the CHARINDEX function to find the position of the delimiter.
- Use the LEFT or SUBSTRING function to extract the text before the delimiter.
- Insert that extracted text into a table variable.
- Update the original string to remove the extracted portion and repeat until no delimiters remain.
CREATE FUNCTION dbo.fn_SplitString (@String NVARCHAR(MAX), @Delimiter CHAR(1)) RETURNS @Results TABLE (Value NVARCHAR(MAX)) AS BEGIN DECLARE @Start INT, @End INT SET @Start = 1 SET @End = CHARINDEX(@Delimiter, @String) WHILE @End > 0 BEGIN INSERT INTO @Results (Value) VALUES (SUBSTRING(@String, @Start, @End - @Start)) SET @Start = @End + 1 SET @End = CHARINDEX(@Delimiter, @String, @Start) END INSERT INTO @Results (Value) VALUES (SUBSTRING(@String, @Start, LEN(@String) - @Start + 1)) RETURN END
Common Mistakes
- Using Multi-Character Delimiters: The STRING_SPLIT function only accepts a single character as a delimiter. If you try to use a string like ', ' (comma followed by a space) as the delimiter, the query will fail. You must use a single character and then use TRIM() to handle any remaining spaces.
- Assuming Order is Preserved: In versions of SQL Server prior to 2022, STRING_SPLIT does not guarantee that the rows will be returned in the same order they appeared in the original string. If the sequence of the items is critical, you cannot rely on the default output.
- Ignoring NULL Values: If the input string passed to STRING_SPLIT is NULL, the function returns an empty result set rather than an error. This can lead to missing data in reports if you are not checking for NULLs in your source columns.
- Overlooking Database Compatibility Level: Even if you are running SQL Server 2017, the STRING_SPLIT function will not work if the database compatibility level is set to a version lower than 130 (SQL Server 2016). You may need to update the compatibility level in the database properties.
Tips
- Use the Ordinal Parameter in SQL Server 2022: If you are using the latest version of SQL Server, you can use
STRING_SPLIT(string, delimiter, 1). Adding the '1' as the third argument enables an "ordinal" column, which tells you the exact position of the split element in the original string, solving the ordering problem. - Combining with STRING_AGG: If you need to split a string, modify the values, and then put them back together into a single string, use STRING_AGG as the inverse of STRING_SPLIT. This is useful for data cleansing tasks.
- Avoid Splitting in Large Loops: While CROSS APPLY is efficient, splitting strings across millions of rows in a high-traffic production environment can be resource-intensive. If you find yourself splitting the same strings repeatedly, consider normalizing your database by moving the delimited lists into a separate related table.
- Handling Case Sensitivity: Remember that the delimiter is case-sensitive if you are using letters as delimiters. Ensure your delimiter matches the case of the characters in your string exactly.
Troubleshooting
If the split operation does not go as planned, follow these steps in order:
- Check for "Invalid function name" errors: If you receive this error, it means your SQL Server version is too old or your database compatibility level is set too low. Verify your version by running
SELECT @@VERSIONand check the compatibility level via the database properties in SSMS. - Verify the Delimiter: If the query runs but returns the entire string as a single row, the delimiter you specified does not exist in the string. Check for hidden characters, such as tabs or non-breaking spaces, which may look like spaces but are different characters.
- Inspect for Empty Results: If you are getting more rows than expected, check for trailing delimiters (e.g., "Apple,Banana,"). A trailing comma will result in an extra empty string row at the end of your result set. Use a WHERE clause to filter these out.
- Test with a Small Dataset: If the query is timing out or running slowly, remove the CROSS APPLY from the main table and test the STRING_SPLIT function on a single hardcoded string. If the single string works quickly, the issue is likely the volume of data or a lack of indexing on the table you are joining.
Frequently Asked Questions
Can I split a string by multiple different delimiters?
The built-in STRING_SPLIT function only supports one delimiter. To split by multiple characters (e.g., commas, semicolons, and pipes), you should first use the REPLACE function to convert all delimiters to a single common character, and then call STRING_SPLIT on that unified string.
Does STRING_SPLIT handle empty strings between delimiters?
Yes, if you have a string like "A,,B", STRING_SPLIT will return three rows: "A", an empty string, and "B". You can remove these by adding a WHERE clause to your query to exclude empty strings.
What is the maximum length of a string that can be split?
The function can handle strings up to the maximum size of the input data type, typically NVARCHAR(MAX) or VARCHAR(MAX), which allows for up to 2GB of text data.
Is there a performance difference between STRING_SPLIT and a custom UDF?
Yes, the built-in STRING_SPLIT function is significantly faster than a custom User-Defined Function because it is implemented internally by the SQL engine. Custom functions, especially those using WHILE loops, introduce overhead that can slow down large queries.
How do I convert the split rows back into a comma-separated list?
You can use the STRING_AGG function (available in SQL Server 2017+) to concatenate values from multiple rows back into a single delimited string.