SUBSTRING() Function in SQL Server
The SUBSTRING() function extracts a substring starting from a position in an input string with a given length. In the case of substring, you need an input string and need to mention the starting point and the total length of the string.
Input : String, start, length output : substring.
Syntax :
Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course by GeeksforGeeks.
SUBSTRING(input_string, start, length);
Parameter :
SUBSTRING function accepts three-parameter like String, start, length. Let’s have a look.
- input_string –It can be a character, binary, text, ntext, or image expression.
- start – It is an integer defining the location where the returned substring starts. The first position in the string is 1.
- length – It is a positive integer that specifies the number of characters to be returned from the substring.
Returns :
It returns a substring with a specified length starting from a location in an input string.
Example-1 :
Using SUBSTRING() function with literal strings.
SELECT SUBSTRING('SQL In Geeksforgeeks', 7, 18 )
AS ExtractString;
Output :
| ExtractString |
|---|
| Geeksforgeeks |
Example-2 :
Using SUBSTRING() function with table columns.
Table -Player_Details
| PlayerId | PlayerName | City |
|---|---|---|
| 45 | Rohit Sharma | Mumbai |
| 18 | Virat Kohli | Bangalore |
| 7 | MS Dhoni | Chennai |
| 33 | Hardik Pandya | Mumbai |
| 42 | Sikhar Dhawan | Delhi |
SELECT SUBSTRING(PlayerName, 1, 5) AS ExtractString FROM Player_Details;
Output :
| ExtractString |
|---|
| Rohit |
| Virat |
| MS Dh |
| Hardi |
| Sikha |

