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)
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)
—
MySQL Tutorials
MySQL Tutorials on this website:
https://www.testingdocs.com/mysql-tutorials-for-beginners/
For more information on MySQL Database: