SQL Substring Function

Mohammed Imtiyaz Dec 9, 2014

Introduction

Substring function in SQL returns the part of a character expression that starts at a specified position and has a specified length. The position parameter and the length parameter must evaluate to integers.

Syntax

SUBSTRING(character_expression, position, length)

character_expression

It is the character expression from which to extract characters.

position

It is an integer that specifies where the substring begins.

length

It is an integer that specifies the length of a substring as number of characters.

Example 1

SELECT SUBSTRING('Aeroplane', 5, 5) AS Output

This query returns five characters beginning with fifth character from a string literal. The output will be :

SQL Substring Function

Example 2

SELECT SUBSTRING('PostalCode', 7, 4) AS Output

This query returns four characters beginning with seventh character from a string literal. The output will be :

SQL Substring Function

Example 3

SELECT SUBSTRING('PostalCode', 7, 60) AS Output

The length argument can exceed the length of the string. In that case, the substring function returns the remainder of the string. The output will be :

SQL Substring Function
Note: Substring uses a one-based index. If the position is 1, the substring begins with first character in character expression.
Tip: Substring returns a null result if the argument is null.