SUBSTRING() Function in SQL Server

Rumman Ansari   Software Engineer   2023-03-25   5473 Share
☰ Table of Contents

Table of Content:


Syntax:


SUBSTRING('Expression', 'Start', 'Length') 

As the name, suggests, this function returns substring (part of the string), from the given expression. You specify the starting location using the 'start' parameter and the number of characters in the substring using 'Length' parameter. All the 3 parameters are mandatory.

Example: Display just the domain part of the given email 'John@bbb.com'.

Code:



Select SUBSTRING('John@bbb.com',6, 7)


Output:

The above code will produce the following result-


 bbb.com

In the above example, we have hardcoded the starting position and the length parameters. Instead of hardcoding we can dynamically retrieve them using CHARINDEX() and LEN() string functions as shown below.


Select SUBSTRING('John@bbb.com',(CHARINDEX('@', 'John@bbb.com') + 1), (LEN('John@bbb.com') - CHARINDEX('@','John@bbb.com')))
Output: bbb.com