How do I use substring to extract a string in MySQL?
In MySQL, you can use the SUBSTRING function to extract a portion of a string.
Its syntax is as follows:
Return a portion of the string ‘str’ starting from the position ‘start’ and with a length of ‘length’.
Among them,
- str: string to be intercepted.
- Start: The initial position (counting from 1).
- Length: the desired amount to be cut.
Here are a few examples:
- Get the first 5 characters of a string.
Get the first five characters from the string ‘Hello World’; The output will be “Hello”.
- Extract the characters from the 6th position to the end of the string.
Select the characters starting from position 6 in the string ‘Hello World’.
– Output: World
- Retrieve the last 5 characters of the string.
– Output: World
- Extract characters from the 2nd to the 7th position of the string:
– Result: ello W
Note: If either start or length is negative, it indicates counting from the end of the string.