In SQL Server, there is no built-in function named SPLIT_PART like in PostgreSQL. Instead, you split strings using STRING_SPLIT (for simple delimited strings) or a combination of LEFT, RIGHT, SUBSTRING, and CHARINDEX for more complex extraction. This article explains the built-in functions, their limitations, and how to achieve the same results as SPLIT_PART.
What Does SPLIT_PART Do in Other Databases?
In PostgreSQL, SPLIT_PART(string, delimiter, position) returns the substring at the specified position in a delimited string. For example, SPLIT_PART('a,b,c', ',', 2) returns 'b'. SQL Server does not have this exact function, but you can replicate it using STRING_SPLIT with a row number, or with string functions if you need a single value without a join.
Using STRING_SPLIT in SQL Server
STRING_SPLIT is a table-valued function introduced in SQL Server 2016. It splits a string into rows based on a delimiter. The syntax is:
SELECT value FROM STRING_SPLIT('apple,banana,cherry', ',');
This returns three rows: apple, banana, cherry. To get the nth element, you need to add a row number using ROW_NUMBER() and filter. For example, to get the second element:
SELECT value FROM (SELECT value, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn FROM STRING_SPLIT('apple,banana,cherry', ',')) AS t WHERE rn = 2;
Note: STRING_SPLIT does not guarantee output order unless you use ORDER BY with a column. In the above, ORDER BY (SELECT NULL) does not guarantee order; SQL Server may return rows in any order. To reliably get the nth element, you need an ordinal position. STRING_SPLIT does not provide an ordinal parameter (that was added only in Azure SQL Database and SQL Server 2022 with the enable_ordinal option). In SQL Server 2022, you can use:
SELECT value FROM STRING_SPLIT('apple,banana,cherry', ',', 1) WHERE ordinal = 2;
This returns banana. If you are on an older version, consider using a JSON-based approach or a custom function.
Replicating SPLIT_PART with String Functions
If you only need a single part and the string is short, you can use CHARINDEX and SUBSTRING. For example, to get the second comma-separated value from a column:
DECLARE @str VARCHAR(100) = 'apple,banana,cherry';
DECLARE @part INT = 2;
SELECT SUBSTRING(@str,
CASE WHEN @part = 1 THEN 1 ELSE CHARINDEX(',', @str, 1) + 1 END,
CASE WHEN @part = 1 THEN CHARINDEX(',', @str) - 1
ELSE CHARINDEX(',', @str, CHARINDEX(',', @str, 1) + 1) - CHARINDEX(',', @str, 1) - 1 END);
This gets messy for parts beyond 2. A cleaner way is to use a recursive CTE or a numbers table. But for most cases, using STRING_SPLIT with ROW_NUMBER() is acceptable if order is not critical or if you can add an identity column.
Using a Custom Split Function
If you need the exact SPLIT_PART behavior repeatedly, you can create a user-defined function that returns the nth part. Here is an example using a WHILE loop:
CREATE FUNCTION dbo.SplitPart
(
@string NVARCHAR(MAX),
@delimiter CHAR(1),
@position INT
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @start INT = 1, @end INT, @part INT = 1;
WHILE @part < @position
BEGIN
SET @end = CHARINDEX(@delimiter, @string, @start);
IF @end = 0
RETURN NULL;
SET @start = @end + 1;
SET @part = @part + 1;
END
SET @end = CHARINDEX(@delimiter, @string, @start);
IF @end = 0
SET @end = LEN(@string) + 1;
RETURN SUBSTRING(@string, @start, @end - @start);
END;
Then call it: SELECT dbo.SplitPart('apple,banana,cherry', ',', 2) returns banana. This works on all versions. However, be cautious with performance if used on large tables, as scalar functions can be slow.
STRING_SPLIT vs. Other Methods: Which to Choose?
Choose based on your SQL Server version and needs:
- SQL Server 2022+: Use
STRING_SPLITwith theenable_ordinalparameter for ordered results. - SQL Server 2016-2019: Use
STRING_SPLITbut be aware of order issues; if order matters, use a different method. - Single value extraction: Use a custom function or string functions if you only need one part.
- Complex parsing: Consider using
OPENJSONif you can convert your string to JSON format.
Common Pitfalls and Workarounds
One common issue is that STRING_SPLIT does not return an ordinal, so the order is not guaranteed. In SQL Server 2016-2019, you can work around this by using a JSON approach. For example, to split and get the second element reliably:
SELECT JSON_VALUE('["apple","banana","cherry"]', '$[1]');
But you need to convert your string to a JSON array. Another pitfall: STRING_SPLIT ignores empty values. If you have consecutive delimiters, it will skip them. For example, STRING_SPLIT('a,,b', ',') returns only a and b. If you need to preserve empty strings, you must use a different method, such as the custom function above or a numbers table.
Performance Considerations
When splitting strings in large queries, performance matters. STRING_SPLIT is generally fast because it is implemented in C++, but it still requires a table scan if you apply it to each row. If you need to split many rows, consider using a permanent numbers table or a tally table to avoid repeated function calls. Also, avoid using scalar UDFs in a SELECT statement for large datasets, as they can cause excessive overhead. Instead, use an inline table-valued function if possible.
Frequently Asked Questions
Does SQL Server have a SPLIT_PART function? No, SQL Server does not have a function named SPLIT_PART. The closest is STRING_SPLIT, which returns rows, not a specific part. You can mimic SPLIT_PART using STRING_SPLIT with ROW_NUMBER() or a custom function.
How do I get the nth element from a comma-separated string in SQL Server? Use STRING_SPLIT with ROW_NUMBER() and filter by the row number, but be aware that order is not guaranteed. For guaranteed order, use SQL Server 2022's enable_ordinal or a custom function that uses CHARINDEX.
Why does STRING_SPLIT not return the order I expect? STRING_SPLIT does not guarantee output order because it does not include an ordinal column. In SQL Server 2022, you can use the enable_ordinal parameter to get an ordinal. In earlier versions, you can use a JSON-based method or a custom split function that tracks position.
Can I use STRING_SPLIT with a column in a SELECT statement? Yes, you can use CROSS APPLY to apply STRING_SPLIT to each row. For example: SELECT s.value FROM MyTable t CROSS APPLY STRING_SPLIT(t.MyColumn, ',') s.
What is the difference between STRING_SPLIT and SPLIT_PART? STRING_SPLIT returns a table of all parts, while SPLIT_PART returns a single part at a specified index. To emulate SPLIT_PART, you need to select the specific row from STRING_SPLIT.
Related
- How Is Progress 8 Calculated? GCSE Scores Explained
- Bosch 36V Brute Tough Drivers: What You Need to Know
- Makita 18V LXT Sub Compact Brushless Drivers: Full Guide
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Not Summing Numbers? Causes and FixesIf Excel is not summing numbers, the most common cause is that some values are stored as text…
- Convert Excel to PowerPoint: Methods, Steps, and TipsTo convert Excel content into a PowerPoint presentation, select the cells or chart in Excel, copy them, and…
- Excel Mac: How to Insert a Row Above or Below a TableTo insert a row in Excel for Mac, select the worksheet row header where the new row should…
- Birthday List Excel Template: Setup and TipsA birthday list Excel template is a worksheet for keeping names, birth dates, and useful reminder details together.…
- Freeze Panes in OpenOffice Calc: Steps and TipsTo freeze panes in OpenOffice Calc, select the cell just below the rows and just to the right…
- How to Double Space in Word for the WebTo double-space text in Word for the web, select the paragraphs you want to change, open Home >…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.