To split a string like ‘s2’ in SQL, you can use the STRING_SPLIT function in SQL Server 2016 and later, or the UNNEST(STRING_TO_ARRAY(...)) construct in PostgreSQL. For example, in SQL Server: SELECT value FROM STRING_SPLIT('s2', ','); returns a single row with value ‘s2’. In PostgreSQL: SELECT unnest(string_to_array('s2', ',')); does the same. This article explains the main methods, how to choose between them, and common pitfalls.
What Does “Split s2” Mean in SQL?
In SQL, “splitting” a string means breaking it into parts based on a delimiter (like a comma, space, or hyphen). The string ‘s2’ is just an example—it could be a single element like ‘s2’ or part of a longer string like ‘s1,s2,s3’. Splitting is useful when you have delimited data stored in a single column and need to turn it into rows for analysis, joining, or reporting. For instance, if a column contains “apple,banana,cherry”, you might want each fruit as a separate row.
How to Split a String in SQL Server
SQL Server provides the STRING_SPLIT function, available from SQL Server 2016 onward (including Azure SQL Database). It takes two arguments: the string to split and the delimiter. The function returns a single column named value containing each substring.
Example: Split the string ‘s1,s2,s3’ by comma.
SELECT value FROM STRING_SPLIT('s1,s2,s3', ',');
Result:
value
-----
s1
s2
s3
If you need the ordinal position (the order of the elements), note that STRING_SPLIT does not guarantee order and does not provide an ordinal column. If you need the position, you can use a ROW_NUMBER() window function, but the order is not guaranteed unless you use a different method (like a JSON-based approach or a recursive CTE).
How to Split a String in PostgreSQL
PostgreSQL offers the string_to_array function to convert a string into an array, and then unnest to expand that array into rows. The syntax is:
SELECT unnest(string_to_array('s1,s2,s3', ','));
Result:
unnest
-------
s1
s2
s3
To include the ordinal position, you can use WITH ORDINALITY:
SELECT * FROM unnest(string_to_array('s1,s2,s3', ',')) WITH ORDINALITY AS t(element, ord);
This returns two columns: element and ord (the 1-based position).
How to Split a String in MySQL and MariaDB
MySQL does not have a built-in split function like SQL Server or PostgreSQL. A common workaround is to use a recursive Common Table Expression (CTE) or a JSON-based trick. For MySQL 8.0+, you can use JSON_TABLE with JSON_EXTRACT after converting the string to a JSON array.
Example: Split ‘s1,s2,s3’ by comma.
SELECT jt.value
FROM JSON_TABLE(CONCAT('["', REPLACE('s1,s2,s3', ',', '","'), '"]'), '$[*]' COLUMNS (value VARCHAR(255) PATH '$')) AS jt;
This works but is less intuitive. Another approach is a recursive CTE that repeatedly extracts substrings until the string is empty. That method works in MySQL 8.0, MariaDB 10.2+, and also in SQL Server (though SQL Server has STRING_SPLIT).
Choosing the Right Method for Your Database
The best method depends on your database system and version:
- SQL Server 2016+: Use
STRING_SPLIT– it’s fast and simple. - PostgreSQL: Use
unnest(string_to_array(...))– it’s idiomatic and supports ordinals. - MySQL 8.0+: Use
JSON_TABLEor a recursive CTE if you need more control. - Oracle: Use
CONNECT BYwithREGEXP_SUBSTRor theAPEX_STRING.SPLITfunction if APEX is installed. - SQLite: Use a recursive CTE or a custom function; there’s no built-in split.
If you only need to split a single value like ‘s2’, you might not even need a function—you can use SUBSTRING and CHARINDEX (SQL Server) or SUBSTRING and POSITION (PostgreSQL) to extract a specific part. But for general splitting, the above methods are standard.
Common Problems and Pitfalls
When splitting strings, watch out for these issues:
- Empty elements: If your string has consecutive delimiters (e.g., ‘s1,,s3’),
STRING_SPLITin SQL Server ignores empty values by default. In PostgreSQL,string_to_arraykeeps empty strings unless you use thenull_stringparameter. To keep empties in SQL Server, you can add aREPLACEtrick or use a different method. - Delimiter in the data: If your data contains the delimiter as part of the value (e.g., ‘s1,s2,with,comma’), splitting naively will break it. You need a more robust parser or a different delimiter.
- Performance: Splitting large strings in a loop can be slow. Set-based methods like
STRING_SPLITare optimized, but if you use a recursive CTE on millions of rows, it may be slow. - Ordering: As mentioned,
STRING_SPLITdoes not guarantee order. If order matters, use a method that provides an ordinal (like PostgreSQL’sWITH ORDINALITYor a JSON approach in SQL Server).
Alternatives to Splitting: Storing Data Properly
Often, the need to split a string indicates a database design problem. Storing delimited lists in a single column violates first normal form (1NF) and makes queries harder. Consider using a junction table (also called a many-to-many table) instead. For example, if you have a table of products and each product has multiple tags, create a product_tags table with columns product_id and tag. This allows efficient indexing, joining, and aggregation. If you must store a list, consider using a native array type (PostgreSQL, BigQuery) or a JSON column (MySQL, SQL Server) that can be queried with JSON functions.
Frequently Asked Questions
Does SQL Server’s STRING_SPLIT preserve order?
No, it does not. The documentation states that the output rows can be in any order. If you need the original order, you must use a different method, such as splitting with a JSON-based approach or using a recursive CTE that tracks the position. In practice, you can often add a ROW_NUMBER() over the result, but that only gives a row number, not the original position unless the split function returns it.
Can I split a string by multiple delimiters at once?
In SQL Server, STRING_SPLIT only accepts a single-character delimiter (or a string of any length, but it treats the whole string as a delimiter, not a set of characters). In PostgreSQL, you can use regexp_split_to_table which accepts a regular expression pattern, so you can split on multiple characters like '[,;]' to split on either a comma or a semicolon. Example: SELECT regexp_split_to_table('a,b;c', '[,;]'); returns ‘a’, ‘b’, ‘c’.
Why does my split return NULL for empty strings?
In PostgreSQL, string_to_array('a,,b', ',') returns an array with an empty string element: {a,"",b}. When you unnest, you get an empty string, not NULL. If you want NULLs, you can use NULLIF or the null_string parameter: string_to_array('a,,b', ',', '') treats empty strings as NULL. In SQL Server, STRING_SPLIT ignores empty substrings by default; if you need to keep them, you can replace the delimiter with a placeholder before splitting, but it’s messy.
Is there a way to split a string in Excel or Google Sheets that I can use in SQL?
No, SQL and spreadsheets are different tools. In Excel, you can use Text to Columns or the TEXTSPLIT function (Excel 365). In Google Sheets, you can use SPLIT(). But these are not SQL functions. If you’re importing data from a spreadsheet into SQL, you might want to do the splitting in the spreadsheet first, or use a SQL function after import.
What if I need to split a string in a SQL query but my database is very old?
For SQL Server 2008 or 2012, STRING_SPLIT is not available. You can use a recursive CTE or a numbers table. A numbers table is a table of integers from 1 to N that you can join to extract substrings using SUBSTRING and CHARINDEX. This method works in any version. For MySQL 5.7, you can use a similar technique with a derived table of numbers. It’s more verbose but reliable.
Can I split a string in SQL without using a function?
Yes, you can use a recursive CTE (common table expression) that repeatedly finds the delimiter and extracts the substring. This works in any database that supports recursive CTEs (SQL Server 2005+, PostgreSQL 8.4+, MySQL 8.0+, Oracle 11g+). The CTE uses CHARINDEX or POSITION to find the delimiter, extracts the part before it, and then recurses on the remainder. This approach is more portable but often slower than built-in functions.
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
- How to Insert a Thick Horizontal Line in Microsoft WordTo add a thick horizontal line in Word, click in the paragraph where you want it, open Home…
- Split Cells in Excel: Shortcut Key and Text to ColumnsIn Excel for Microsoft 365 on Windows, select the cell or column containing the text, then press Alt,…
- Excel SUM: How to Exclude Hidden Rows and Filtered RowsYes. To sum visible rows while excluding both filtered-out rows and rows hidden manually, use SUBTOTAL with function…
- Excel: How to Hide Rows in a Table (3 Ways)The fastest way to hide rows in an Excel table is to select the row(s), right-click, and choose…
- Compressing Images in PowerPoint: Steps and SettingsIn PowerPoint for Microsoft 365 on Windows, select a picture, go to Picture Format > Compress Pictures, choose…
- Excel Data Validation Drop-Down Not Showing? FixesIf an Excel data validation drop-down is not showing, select the cell and check Data > Data Validation…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.