MySQL does not have a built-in SPLIT() function like some other databases, but you can split strings using the SUBSTRING_INDEX() function combined with LENGTH() and REPLACE(), or by using a recursive Common Table Expression (CTE) to return each piece as a separate row. The simplest way to split a comma-separated string into multiple values is to use SUBSTRING_INDEX() in a loop or with a numbers table, and for MySQL 8.0+, a recursive CTE provides a clean, set-based solution.
Why MySQL Lacks a Native SPLIT Function
Unlike PostgreSQL (which has string_to_array()) or SQL Server (which has STRING_SPLIT()), MySQL does not provide a built-in function that directly splits a string into rows. This is partly due to MySQL’s historical focus on simplicity and its different approach to set-based operations. Instead, MySQL offers SUBSTRING_INDEX(), which extracts a substring from a string before or after a specified number of delimiters. This function is the building block for most manual splitting techniques.
For example, SUBSTRING_INDEX('apple,banana,cherry', ',', 1) returns 'apple', and SUBSTRING_INDEX('apple,banana,cherry', ',', -1) returns 'cherry'. To get the middle element, you need to nest calls. This works well for a fixed number of parts, but for an unknown number, you need a more dynamic approach.
Using SUBSTRING_INDEX to Split a String
The most common method to split a delimited string into multiple rows is to use a helper table of numbers (or a recursive CTE) to iterate through the string. Here’s a step-by-step example using a numbers table approach:
- Create a table with numbers from 1 to a maximum number of parts you expect (e.g., 10).
- Join your string with the numbers table using a condition that checks if the delimiter exists at that position.
- Use
SUBSTRING_INDEX()to extract each part.
Example: Assume you have a table items with a column tags containing comma-separated values like 'red,green,blue'.
-- Create a numbers table (or use a CTE)
CREATE TABLE numbers (n INT PRIMARY KEY);
INSERT INTO numbers VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
-- Split the string
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(items.tags, ',', numbers.n), ',', -1) AS tag
FROM items
JOIN numbers ON numbers.n <= (LENGTH(items.tags) - LENGTH(REPLACE(items.tags, ',', ''))) + 1;
This works by counting the number of commas (using LENGTH and REPLACE) to determine how many parts exist, then extracting each part with a nested SUBSTRING_INDEX. The result for 'red,green,blue' would be three rows: 'red', 'green', 'blue'.
Recursive CTE Method (MySQL 8.0+)
If you’re using MySQL 8.0 or later, a recursive Common Table Expression (CTE) is a cleaner and more efficient way to split strings without needing a numbers table. Here’s how it works:
WITH RECURSIVE split_cte AS (
SELECT
'apple,banana,cherry' AS full_string,
1 AS pos,
SUBSTRING_INDEX('apple,banana,cherry', ',', 1) AS part
UNION ALL
SELECT
full_string,
pos + 1,
SUBSTRING_INDEX(SUBSTRING_INDEX(full_string, ',', pos + 1), ',', -1)
FROM split_cte
WHERE pos < (LENGTH(full_string) - LENGTH(REPLACE(full_string, ',', ''))) + 1
)
SELECT part FROM split_cte;
This recursive CTE starts with the first part, then repeatedly extracts the next part until the position exceeds the total number of parts. The output is a single column with each split value as a separate row. You can adapt this to work with a table column by replacing the literal string with a column reference and adding a CROSS JOIN or using it in a subquery.
Choosing Between Methods
Which method you choose depends on your MySQL version and your specific use case:
- MySQL 5.7 and earlier: The numbers table approach is the standard because recursive CTEs are not available. You’ll need to create a numbers table or use a derived table with
UNION ALLto generate numbers. - MySQL 8.0+: The recursive CTE is more readable and doesn’t require an extra table. It’s also more efficient for large strings because it stops when the string is exhausted.
- Fixed number of parts: If you know the exact number of delimiters (e.g., splitting a date ‘2023-01-15’ into three parts), you can simply use nested
SUBSTRING_INDEX()calls without loops. - Performance: For very large datasets, the numbers table join can be faster if the numbers table is indexed and you’re splitting a column from many rows. The recursive CTE may have recursion depth limits (default 1000), but that’s rarely an issue for typical strings.
Common Problems and Pitfalls
When splitting strings in MySQL, you may encounter several issues:
- Empty strings: If the string has consecutive delimiters (e.g., ‘a,,b’),
SUBSTRING_INDEXwill return empty strings for those positions. You may need to filter them out with aWHEREclause. - Trailing delimiters: A string like ‘a,b,’ will produce an empty last element. Decide whether you want to include it or trim the string first.
- Delimiter length: The methods above assume a single-character delimiter. For multi-character delimiters (like ‘||’), you need to adjust the
LENGTHcalculation: useLENGTH(REPLACE(full_string, '||', ''))divided by the delimiter length, and theSUBSTRING_INDEXcalls need to use the exact delimiter string. - NULL values: If the column is NULL, the split will return NULL. Use
COALESCEorIFNULLto handle that.
Alternatives to Splitting in MySQL
Sometimes splitting a string is not the best approach. Consider these alternatives:
- Normalize your schema: Instead of storing comma-separated values in a single column, use a separate junction table. This is the relational database best practice and avoids the need to split at all.
- Use JSON functions: If you store data as a JSON array (e.g.,
["red","green"]), you can useJSON_TABLE()(MySQL 8.0+) to expand it into rows. This is more robust than string splitting. - Use
FIND_IN_SET(): For simple checks like ‘is value X in the list’,FIND_IN_SET()can be used directly without splitting. For example,FIND_IN_SET('green', 'red,green,blue')returns 2. - Use
REGEXP_SUBSTR()(MySQL 8.0+): This function can extract substrings based on a regular expression, which can be useful for more complex splitting patterns.
Frequently Asked Questions
Does MySQL have a SPLIT() function like SQL Server?
No, MySQL does not have a built-in SPLIT() function. You must use SUBSTRING_INDEX() or a recursive CTE to achieve the same result. Some third-party tools or user-defined functions (UDFs) exist, but they require installation and are not part of standard MySQL.
How can I split a string into multiple columns instead of rows?
If you need a fixed number of columns, you can use SUBSTRING_INDEX() with different positions. For example, to split ‘first,last’ into two columns: SUBSTRING_INDEX(str, ',', 1) as first, SUBSTRING_INDEX(str, ',', -1) as last. For variable numbers, you’d need to use a pivot query, which is more complex.
Can I split a string in a SELECT statement without creating a table?
Yes, you can use a derived table or a recursive CTE directly in a query. For example, WITH RECURSIVE ... SELECT ... works in a single statement. For MySQL 5.7, you can use a subquery that generates numbers with UNION ALL.
What is the maximum recursion depth for a recursive CTE in MySQL?
The default maximum recursion depth is 1000 iterations, but you can increase it with the cte_max_recursion_depth system variable. For splitting strings, this is rarely a concern because strings are typically short.
Is it faster to split in MySQL or in my application code?
It depends on the amount of data. For small datasets, splitting in application code (e.g., PHP, Python) is often simpler and more readable. For large datasets, doing it in MySQL reduces data transfer and can be optimized with indexes, but the split operation itself can be CPU-intensive. Benchmark your specific case.
How do I handle a delimiter that appears inside quoted values?
None of the basic methods handle quoted delimiters (e.g., ‘a,”b,c”,d’). For CSV-like data with quotes, you should use a proper CSV parser in your application, or use LOAD DATA INFILE with the FIELDS ENCLOSED BY option if importing from a file. Splitting such strings in MySQL is not recommended.
Related
- Computer Data Entry Job Vacancy: Real Answers
- How to Select a Cell and Everything Below It in Excel
- SQL Difficult Queries: Real-World Examples & Solutions
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel MONTH Function Examples: Formulas and TipsExcel’s MONTH function extracts the month number from a date, returning an integer from 1 (January) to 12…
- Microsoft Excel Profit and Loss Template: Setup & FormulasYes. In Excel for Microsoft 365 on Windows, choose File > New and search for “profit and loss”…
- How to Make a Filter in Excel: Step-by-StepTo make a filter in Excel for Microsoft 365 on Windows, click a cell in your data, then…
- Excel TEXT Function Format Codes ExplainedExcel TEXT format codes are patterns you pass to the TEXT function to turn a number, date, time,…
- Excel Formula for File Path: Get the Workbook LocationIn Excel for Microsoft 365 on Windows, use =CELL("filename",A1) to return the saved workbook’s path, file name, and…
- Excel Cell Protection Options: Lock Cells the Right WayExcel cell protection has three main parts: mark cells as Locked or Hidden, then use Protect Sheet to…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.