MySQL SUBSTRING() Function
In MySQL, the The SUBSTRING() function returns a substring of a specified string starting starting at a specified position. SUBSTRING() is the same as SUBSTR().
SUBSTRING() Syntax
MySQL the SUBSTRING() function have 4 forms of syntax:
SUBSTRING(str, pos)
SUBSTRING(str FROM pos)
SUBSTRING(str, pos, len)
SUBSTRING(str FROM pos FOR len)
MID(str, pos, len) is equivalent to SUBSTRING(str, pos, len).
Parameters
str- Required. The original string from which to extract the substring.
pos- Required. The location to start extracting a substring. It can be positive or negative. If it is negative, the beginning of the substring is
poscharacters from the end of the string, rather than the beginning. len- Optional. The length (number of characters) of the substring. If not specified, extract to the end of the original string.
Return value
The SUBSTRING() function returns a substring of a specified string starting starting at a specified position.
- If
poseqauls or exceeds the length of the original string, the function will return an empty string''. - If
posis negative, the function returns an empty string''. - If the parameter is
NULL, the function will returnNULL.
SUBSTRING() Examples
SELECT
SUBSTRING('Hello', 1, 2),
SUBSTRING('Hello', 2, 2),
SUBSTRING('Hello', 1),
SUBSTRING('Hello', 1, 8),
SUBSTRING('Hello', -2, 2),
SUBSTRING('Hello', 8, 2),
SUBSTRING('Hello', 0, 2),
SUBSTRING('Hello', 0),
SUBSTRING('Hello' FROM 2 FOR 2)\G
SUBSTRING('Hello', 1, 2): He
SUBSTRING('Hello', 2, 2): el
SUBSTRING('Hello', 1): Hello
SUBSTRING('Hello', 1, 8): Hello
SUBSTRING('Hello', -2, 2): lo
SUBSTRING('Hello', 8, 2):
SUBSTRING('Hello', 0, 2):
SUBSTRING('Hello', 0):
SUBSTRING('Hello' FROM 2 FOR 2): el