How to Use the SUBSTRING() Function in SQL Server: A Complete Guide

Rumman Ansari   Software Engineer   2024-07-21 09:36:46   5480  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

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