Substring() in SQL Server: How to use Function with Example

What is Substring()?

Substring() is a function in SQL which allows the user to derive substring from any given string set as per user need. Substring() extracts a string with a specified length, starting from a given location in an input string. The purpose of Substring() in SQL is to return a specific portion of the string.

Syntax for Substring()

SUBSTRING(Expression, Starting Position, Total Length)

Here,

Rules for using SUBSTRING():

Below Diagram illustrate the use of SUBSTRING() function in SQL server.

How Substring() in SQL Works

T-SQ Substring Examples:

Assumption: Assume that we have the table as 'gtupapers' with two columns and four rows as displayed below:

We will use 'gtupapers' table in further examples

Query 1: SUBSTRING() in SQL with length less than Total Maximum length of expression

SELECT Tutorial_name, SUBSTRING(Tutorial_name,1,2) As SUB from gtupapers;

Result: Below diagram display substring of 'Tutorial_name' column as 'SUB' column

Query 2: SUBSTRING() in SQL server with the length greater than Total Maximum length of expression.

SELECT Tutorial_name, SUBSTRING(Tutorial_name,2,8) As SUB from gtupapers;

Result: Below diagram display substring of 'Tutorial_name' column as 'SUB' column. Here in spite of

Substring length is greater than Total Maximum length of expression, and no error and query return full string returned.

Summary:

 

YOU MIGHT LIKE: