SUBSTRING
Descriptionβ
The SUBSTRING function is used to extract a substring from a string. You can specify the starting position and length, supporting both forward and backward extraction. The position of the first character in the string is 1.
Aliasβ
SUBSTR
Syntaxβ
SUBSTRING(<str>, <pos> [, <len>])
Parametersβ
Parameter | Description |
---|---|
<str> | Source string. Type: VARCHAR |
<pos> | Starting position, can be negative. Type: INT |
<len> | Optional parameter, length to extract. Type: INT |
Return Valueβ
Returns VARCHAR type, representing the extracted substring.
Special cases:
- If any parameter is NULL, returns NULL
- If pos is 0, returns an empty string
- If pos is negative, counts from the end of the string backwards
- If pos exceeds the string length, returns an empty string
- If len is not specified, returns all characters from pos to the end of the string
Examplesβ
- Basic usage (specify starting position)
SELECT substring('abc1', 2);
+-----------------------------+
| substring('abc1', 2) |
+-----------------------------+
| bc1 |
+-----------------------------+
- Using negative position
SELECT substring('abc1', -2);
+-----------------------------+
| substring('abc1', -2) |
+-----------------------------+
| c1 |
+-----------------------------+
- Case when position is 0
SELECT substring('abc1', 0);
+----------------------+
| substring('abc1', 0) |
+----------------------+
| |
+----------------------+
- Position exceeds string length
SELECT substring('abc1', 5);
+-----------------------------+
| substring('abc1', 5) |
+-----------------------------+
| |
+-----------------------------+
- Specifying length parameter
SELECT substring('abc1def', 2, 2);
+-----------------------------+
| substring('abc1def', 2, 2) |
+-----------------------------+
| bc |
+-----------------------------+