Curriculum
Course: SQL
Login

Curriculum

SQL

SQL References

0/80

MySQL Functions

0/139

SQL Server Functions

0/84

SQL Quick Ref

0/1
Text lesson

SUBSTRING

Example

Retrieve a portion of a string by beginning at the fifth position and extracting three characters.

SELECT SUBSTRING(“SQL Tutorial”, 5, 3) AS ExtractString; 

Definition and Usage

The SUBSTRING() function retrieves a substring from a string, beginning at any position.

Note: The first character of the string is at position 1.

1 2 3 4 5 6 7 8 9 10 11 12

S Q L T u t o r i a l

Note: The last character of the string is at position -1.

-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

S Q L T u t o r i a l

Note: The SUBSTR() and MID() functions are equivalent to the SUBSTRING() function.

Syntax

SUBSTRING(string, start, length)

OR:

SUBSTRING(string FROM start FOR length)

Parameter Values

Parameter

Description

string

Mandatory. Specifies the string from which extraction is required.

start

Necessary. Indicates the starting position, which can be either positive or negative. A positive value signifies extraction from the beginning of the string, while a negative value denotes extraction from the end of the string.

length

Optional. Specifies the quantity of characters to extract. If left unspecified, the function returns the entire string starting from the specified position.

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Retrieve a substring from the text within a column, starting at position 2, and extracting 5 characters.

SELECT SUBSTRING(CustomerName, 2, 5) AS ExtractString
FROM Customers; 

Example

Retrieve a substring from a string, starting from the fifth position from the end, and extract 5 characters.

SELECT SUBSTRING(“SQL Tutorial”, 5, 5) AS ExtractString;