Skip to content

Instantly share code, notes, and snippets.

@fedecarg
Last active October 22, 2018 12:33
Show Gist options
  • Save fedecarg/5107155 to your computer and use it in GitHub Desktop.
Save fedecarg/5107155 to your computer and use it in GitHub Desktop.
MySQL Split String Function

MySQL Split String Function

The following example function takes 3 parameters, performs an operation using an SQL function, and returns the result.

Function

CREATE FUNCTION SPLIT_STR(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '');

Usage

SELECT SPLIT_STR(string, delimiter, position)

Example

SELECT SPLIT_STR('a|bb|ccc|dd', '|', 3) as third;

+-------+
| third |
+-------+
| ccc   |
+-------+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment