String slicing
On this page
Returns a range of Unicode characters from a string.
Syntax
<string>[<start>:<end>]
<string>[:<end>]
<string>[<start>:]
<string>[:]Arguments
| Argument | Type | Description |
|---|---|---|
<string> | string | String to slice. |
<start> | int | Optional inclusive position, starting at 0. Negative values count from the end. Omitted or NULL starts at the first character. |
<end> | int | Optional exclusive position. Negative values count from the end. Omitted or NULL continues to the end. |
Returns
Returns string.
- Positions outside the string are limited to its start or end.
- If the adjusted start index is greater than or equal to the adjusted end index, returns an empty string.
- A NULL input returns NULL.
Usage notes
Positions count Unicode characters, not UTF-8 bytes.
Examples
Read a fixed-format event identifier
Extract the producer prefix and sequence from an identifier with a known layout.
VALUES ('web-000017'), ('app-000042')
SELECT $0 AS event_id
SELECT event_id, event_id[:3] AS producer, event_id[-6:] AS sequence+------------+----------+----------+
| event_id | producer | sequence |
+------------+----------+----------+
| web-000017 | web | 000017 |
| app-000042 | app | 000042 |
+------------+----------+----------+The prefix excludes index 3; the negative start selects the last six characters.
Preview international feedback
Take the first four characters of a customer message without splitting UTF-8 bytes.
SELECT '结账等待时间太长'[0:4] AS preview+----------+
| preview |
+----------+
| 结账等待 |
+----------+