Retrieve a portion of a string by beginning at the fifth position and extracting three characters.
SELECT SUBSTRING(“SQL Tutorial”, 5, 3) AS ExtractString; |
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.
SUBSTRING(string, start, length) |
OR:
SUBSTRING(string FROM start FOR length) |
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. |
Works in: | From MySQL 4.0 |
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; |
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; |