w3resource logo


MySQL substring index function

MySQL SUBSTRING_INDEX() function

rating Average rating 8 out of 10. Total 79 users rated.

<<PreviousNext>>

Description

MySQL SUBSTRING_INDEX() returns the substring from the given string before a specified number of occurrences of a delimiter.

The substring returned from the left of the final delimiter when the specified number is a positive number and from right of the final delimiter when the specified number is a negative number.

If the specified number is greater than the number of occurrence of delimiter, the returned substring will be the total string. If the specified number is 0, nothing will be fetched from the given string.

Syntax

SUBSTRING_INDEX(str, delim, count)

Argument

Name Description
str A string.
delim A delimiter.
count An integer indicating the number of occurrences of delim.

Example : MySQL SUBSTRING_INDEX() function

The following MySQL statement returns the substring form the left of the final delimiter i.e. 2nd delimiter (.) from the given string ‘www.mytestpage.info’. Counting starts from the left of the string.

Code

SELECT SUBSTRING_INDEX('www.mytestpage.info','.',2);

Output

MySQL SUBSTRING_INDEX()

Pictorial Presentation

MySQL SUBSTRING_INDEX() with positive value

Example of MySQL SUBSTRING_INDEX() function using negative count

The following MySQL statement returns the substring form the right of the final delimiter i.e. 2nd delimiter (.) from the given string ‘www.mytestpage.info’. Counting starts from the right of the string.

Code

SELECT SUBSTRING_INDEX('www.mytestpage.info','.',-2); 

Output

MySQL SUBSTRING_INDEX() EXAMPLE

Pictorial Presentation

MySQL SUBSTRING_INDEX() with negative value

Example : Split an IP address into 4 respective octets using MySQL SUBSTRING_INDEX() function

The following MySQL command splits an IP address into 4 respecting octets (unit of digital information). Assume the IP addresses are stored in a sample table called 'log_file'.

mysql> SELECT ip, SUBSTRING_INDEX(ip,'.',1) AS part1, 
SUBSTRING_INDEX(SUBSTRING_INDEX(ip,'.',2),'.',-1) AS part2, 
SUBSTRING_INDEX(SUBSTRING_INDEX(ip,'.',-2),'.',1) AS part3, 
SUBSTRING_INDEX(ip,'.',-1) AS part4  FROM log_file;
+-----------------+-------+-------+-------+-------+
| ip              | part1 | part2 | part3 | part4 |
+-----------------+-------+-------+-------+-------+
| 127.0.0.1       | 127   | 0     | 0     | 1     |
| 192.128.0.15    | 192   | 128   | 0     | 15    |
| 255.255.255.255 | 255   | 255   | 255   | 255   |
+-----------------+-------+-------+-------+-------+
3 rows in set (0.00 sec)

All String Functions

MySQL String Functions, slide presentation



We have compiled a number of MySQL Questions and Answers. Check and assess you MySQL skill by visiting those questions and answers.

<<PreviousNext>>