SQL Tutorial SQL Advanced SQL Database SQL References

MySQL SUBSTR() Function



The MySQL SUBSTR() function is used to extract a substring from a string starting from specified position.

The SUBSTR() and MID() functions are synonyms of the SUBSTRING() function.

Syntax

/* version 1 */
SUBSTR(string, start, length)

/* version 2 */
SUBSTR(string FROM start FOR length)

Parameters

string Required. Specify the string to extract from.
start Required. Specify the start position. It can be both a positive or negative number.
  • If it is a positive number, this function extracts from the beginning of the string.
  • If it is a negative number, this function extracts from the end of the string.
Note that the first position in string starts with 1.
length Optional. Specify the number of characters to extract. If omitted, the whole string will be returned (from the start position).

Return Value

Returns the substring extracted from specified string.

Example 1:

The example below shows the usage of SUBSTR() function.

mysql> SELECT SUBSTR('AlphaCodingSkills.com', 1);
Result: 'AlphaCodingSkills.com'

mysql> SELECT SUBSTR('AlphaCodingSkills.com' FROM 1);
Result: 'AlphaCodingSkills.com'

mysql> SELECT SUBSTR('AlphaCodingSkills.com', 6);
Result: 'CodingSkills.com'

mysql> SELECT SUBSTR('AlphaCodingSkills.com' FROM 6);
Result: 'CodingSkills.com'

mysql> SELECT SUBSTR('AlphaCodingSkills.com', 6, 6);
Result: 'Coding'

mysql> SELECT SUBSTR('AlphaCodingSkills.com' FROM 6 FOR 6);
Result: 'Coding'

mysql> SELECT SUBSTR('AlphaCodingSkills.com', -4, 4);
Result: '.com'

mysql> SELECT SUBSTR('AlphaCodingSkills.com' FROM -4 FOR 4);
Result: '.com'

Example 2:

Consider a database table called Employee with the following records:

PhoneNumberEmpIDAddress
+33-14XXXXX011Grenelle, Paris, France
+31-20XXXXX192Geuzenveld, Amsterdam, Netherlands
+86-10XXXXX4583Yizhuangzhen, Beijing, China
+65-67XXXXX44Yishun, Singapore
+81-35XXXXX725Koto City, Tokyo, Japan

In the query below, the SUBSTR() function is used to extract the country code from the PhoneNumber column records.

SELECT *, SUBSTR(PhoneNumber, 2, 2) AS CountryCode 
FROM Employee;

This will produce the result as shown below:

PhoneNumberEmpIDAddressCountryCode
+33-14XXXXX011Grenelle, Paris, France33
+31-20XXXXX192Geuzenveld, Amsterdam, Netherlands31
+86-10XXXXX4583Yizhuangzhen, Beijing, China86
+65-67XXXXX44Yishun, Singapore65
+81-35XXXXX725Koto City, Tokyo, Japan81

❮ MySQL Functions

5