Curriculum
Course: MYSQL
Login

Curriculum

MYSQL

MySQL References

0/140
Text lesson

SUBSTR

Example

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

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

Definition and Usage

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

Note: The first character in 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 in the string is positioned at -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: Both the SUBSTR() and MID() functions are equivalent to the SUBSTRING() function.

Syntax

SUBSTR(stringstartlength)

OR:

SUBSTR(string FROM start FOR length)

Parameter Values

Parameter

Description

string

Mandatory. The string from which extraction is required.

start

Necessary. Specifies the starting position, which can be either positive or negative. A positive number indicates extraction from the beginning of the string, while a negative number indicates extraction from the end of the string.

length

Optional. Specifies the quantity of characters to extract. If not provided, the entire string from the starting position will be returned.

Technical Details

Works in: From MySQL 4.0

More Examples

Example

Retrieve a substring from the text within a column, beginning at the second position and extracting five characters.

SELECT SUBSTR(CustomerName, 2, 5AS ExtractString
FROM Customers; 

Example

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

SELECT SUBSTR(“SQL Tutorial”, –55AS ExtractString;