> ## Documentation Index
> Fetch the complete documentation index at: /documents/llms.txt
> Use this file to discover all available pages before exploring further.

# substring, substr

> 从指定位置开始提取指定长度的子字符串。

从指定位置开始提取字符，并返回指定长度的子字符串。

## 语法

```Haskell theme={null}
VARCHAR substr(VARCHAR str, pos[, len])
```

## 参数

* `str`：必需，待提取字符的字符串。必须是 VARCHAR 值。
* `pos`：必需，指定起始位置的整数。注意，字符串中的第一个字符是 1，而不是 0。
  * 如果 `pos` 为 0，则返回空字符串。
  * `pos` 可以是负整数。在这种情况下，该函数从字符串末尾开始提取字符。参见示例 2。
  * 如果 `pos` 指定的位置超出字符串范围，则返回空字符串。参见示例 3。
* `len`：可选，指定要提取字符数的正整数。
  * 如果指定了 `len`，该函数从 `pos` 指定的位置开始提取 `len` 个字符。
  * 如果未指定 `len`，该函数提取从 `pos` 开始的所有字符。参见示例 1。
  * 如果 `len` 超过匹配字符的实际长度，则返回所有匹配字符。参见示例 4。

## 返回值

返回 VARCHAR 类型的值。

## 示例

```Plain Text theme={null}
-- 从第一个字符 "s" 开始提取所有字符。
MySQL > select substring("starrockscluster", 1);
+-------------------------------------+
| substring('starrockscluster', 1)    |
+-------------------------------------+
| starrockscluster                    |
+-------------------------------------+

-- 从第一个字符 "s" 开始提取前 9 个字符。
MySQL > select substring("starrockscluster", 1, 9);
+-------------------------------------+
| substring('starrockscluster', 1, 9) |
+-------------------------------------+
| starrocks                           |
+-------------------------------------+

-- 位置为负数，从字符串末尾开始计数。
MySQL > select substring("starrocks", -5, 5);
+-------------------------------+
| substring('starrocks', -5, 5) |
+-------------------------------+
| rocks                         |
+-------------------------------+

-- 位置超出字符串长度，返回空字符串。
MySQL > select substring("apple", 8, 2);
+--------------------------------+
| substring('apple', 8, 2)       |
+--------------------------------+
|                                |
+--------------------------------+

-- 有 5 个匹配字符。长度 9 超过匹配字符的长度，返回所有匹配字符。
MySQL > select substring("apple", 1, 9);
+--------------------------+
| substring('apple', 1, 9) |
+--------------------------+
| apple                    |
+--------------------------+
```

## 关键词

substring,string,sub


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.