SQL Server Tutorial SQL Server Advanced SQL Server Database SQL Server References

SQL Server SUBSTRING() Function



The SQL Server (Transact-SQL) SUBSTRING() function is used to extract a substring from a string starting from specified position.

Syntax

SUBSTRING(string, start, length)

Parameters

string Required. Specify the string to extract from.
start Required. Specify the start position.
  • If start is less than 1, the returned expression will begin at the first character and the number of characters that are returned is the largest value of either the sum of (start + length - 1) or 0.
  • If start is greater than the number of characters in the string, a zero-length expression is returned.
Note that the first position in string starts with 1.
length Required. Specify the number of characters to extract.
  • If length is negative, an error is returned.
  • If the sum of start and length is greater than the number of characters in the string, the whole string beginning at start is returned.

Return Value

Returns the substring extracted from specified string.

Example 1:

The example below shows the usage of SUBSTRING() function.

SELECT SUBSTRING('AlphaCodingSkills.com', 1, 100);
Result: 'AlphaCodingSkills.com'

SELECT SUBSTRING('AlphaCodingSkills.com', 6, 100);
Result: 'CodingSkills.com'

SELECT SUBSTRING('AlphaCodingSkills.com', 6, 6);
Result: 'Coding'

SELECT SUBSTRING('AlphaCodingSkills.com', -4, 10);
Result: 'Alpha'

Example 2:

Consider a database table called Employee with the following records:

PhoneNumberEmpIDAddress
+33-1479961011Grenelle, Paris, France
+31-2011503192Geuzenveld, Amsterdam, Netherlands
+86-10997324583Yizhuangzhen, Beijing, China
+65-672348244Yishun, Singapore
+81-3577990725Koto City, Tokyo, Japan

In the query below, the SUBSTRING() function is used to extract the country code from the PhoneNumber column records.

SELECT *, SUBSTRING(PhoneNumber, 2, 2) AS CountryCode 
FROM Employee;

This will produce the result as shown below:

PhoneNumberEmpIDAddressCountryCode
+33-1479961011Grenelle, Paris, France33
+31-2011503192Geuzenveld, Amsterdam, Netherlands31
+86-10997324583Yizhuangzhen, Beijing, China86
+65-672348244Yishun, Singapore65
+81-3577990725Koto City, Tokyo, Japan81

❮ SQL Server Functions