SUBSTRING() function in MySQL

SUBSTRING() :
function in MySQL is used to derive substring from any given string .It extracts a string with a specified length, starting from a given location in an input string. The purpose of substring is to return a specific portion of the string.

Syntax :

SUBSTRING(string, start, length)
OR
SUBSTRING(string FROM start FOR length)

Parameters :
This method accepts three-parameter as mentioned above and described below.

  • string –
    Input String from which to extract.
  • start –
    The starting position. 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.
  • length –
    It is optional. It identifies the number of characters to extract. If it is not given The whole string is returned from the starting position.

Example-1 :
Deriving substring from a given string without giving length parameter.

SELECT SUBSTRING("GeeksForGeeks", 3) AS Sub_String;

Output :



Sub_String
eksForGeeks

Example-2 :
Deriving substring from a given string when length parameter is given.

SELECT SUBSTRING("GeeksForGeeks", 3, 8) AS Sub_String; 

Output :

Sub_String
eksForGe

Example-3 :
Deriving substring from a given string when starting position is -ve, i.e: starting from end.

 
SELECT SUBSTRING("GeeksForGeeks", -3 ) AS Sub_String; 

Output :



Sub_String
eks

Example-4 :
Extracting all substring from the text column in a Table.

Table : Student_Details

Student_Id Student_Name
101 Virat
102 Rohit
103 Rahul
104 Sikhar

SELECT SUBSTRING( Student_Name, 2 ) AS Sub_String FROM Student_Details ;

Output :

Sub_String
irat
ohit
ahul
ikhar

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.