Database

MySQL SUBSTRING_INDEX Function

MySQL SUBSTRING_INDEX Function

In this tutorial, we will learn about the MySQL SUBSTRING_INDEX function with some examples. This function returns the substring from the given string before counting the occurrences of the delimiter.

Syntax

The general syntax of the function is as follows:

SUBSTRING_INDEX(<string>, <delimiter>, <count>)

The function searches the given string for the count occurrence of delimiter and returns the characters searched through when hitting the count. If the count is positive the function searches the string from the left. If the count is negative the function searches the string from the right.

The SUBSTRING_INDEX() function performs a case-sensitive search for the delimiter.

Examples

mysql> SELECT SUBSTRING_INDEX(‘www.TestingDocs.com’,’.’,1);
+———————————————-+
| SUBSTRING_INDEX(‘www.TestingDocs.com’,’.’,1) |
+———————————————-+
| www |
+———————————————-+
1 row in set (0.01 sec)

mysql> SELECT SUBSTRING_INDEX(‘www.TestingDocs.com’,’.’,-2);
+———————————————–+
| SUBSTRING_INDEX(‘www.TestingDocs.com’,’.’,-2) |
+———————————————–+
| TestingDocs.com |
+———————————————–+
1 row in set (0.00 sec)

 

MySQL SUBSTRING_INDEX Function

 

Let’s see another example, where the delimiter is not present in the given string. The function returns the whole string.

mysql> SELECT SUBSTRING_INDEX(‘www.TestingDocs.com’,’@’,1);
+———————————————-+
| SUBSTRING_INDEX(‘www.TestingDocs.com’,’@’,1) |
+———————————————-+
| www.TestingDocs.com |
+———————————————-+
1 row in set (0.00 sec)

 

SUBSTRING_INDEX Delimiter not found

Sample Quiz

What will be the result of the following query?

mysql> SELECT SUBSTRING_INDEX(‘www.testingdocs.com’, ‘.’, -2);

A) www.testing
B) testingdocs.com
C) com
D) testingdocs

Correct Answer
B) testingdocs.com

Explanation

The SUBSTRING_INDEX() function splits the string based on the specified delimiter and returns a part of the string. Here, ‘.’ is the delimiter, and -2 specifies the last two parts from the right.

So, it returns ‘testingdocs.com‘.

MySQL Tutorials

MySQL Tutorials on this website: