Retrieve a substring from a string starting at position 5 and extracting 3 characters
SELECT MID(“SQL Tutorial”, 5, 3) AS ExtractString; |
The MID() function extracts a substring from a string starting 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
The last character in 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 MID() and SUBSTR() functions are equivalent to the SUBSTRING() function.
MID(string, start, length) |
Parameter |
Description |
string |
Input required: The string from which the substring will be extracted. |
start |
Input required: The start position, which can be either positive or negative. If positive, the function extracts from the beginning of the string. If negative, it extracts from the end of the string. |
length |
Input required: The number of characters to extract from the string. |
Works in: | From MySQL 4.0 |
Retrieve a substring from the text in a column starting at position 2 and extracting 5 characters.
SELECT MID(CustomerName, 2, 5) AS ExtractString FROM Customers; |
Retrieve a substring from a string starting from the end, at position -5, and extract 5 characters.
SELECT MID(“SQL Tutorial”, –5, 5) AS ExtractString; |