How to extract the last few characters of a string in mysql?
In MySQL, you can use the SUBSTRING function to extract the last few characters of a string. SUBSTRING function has two different usages:
- Use the SUBSTRING function to extract the last few characters of a string.
SELECT SUBSTRING(column_name, -n) FROM table_name;
In this case, column_name is the name of the column where the string to be extracted is located, table_name is the name of the table, and n is the number of characters to be extracted from the end. A negative number indicates counting from the end of the string backwards.
For example, to extract the last 5 characters of the string “Hello World”:
SELECT SUBSTRING('Hello World', -5);
The output result is “World”
- Use the combination of the SUBSTRING function and CHAR_LENGTH function to extract the last few characters of a string.
SELECT SUBSTRING(column_name, CHAR_LENGTH(column_name) - n + 1) FROM table_name;
其中,column_name represents the name of the column where the string to be extracted is located, table_name is the name of the table, and n is the number of characters to be extracted from the end.
For example, to extract the last 5 characters of the string “Hello World”:
SELECT SUBSTRING('Hello World', CHAR_LENGTH('Hello World') - 4);
The output is “World”.
Note: When using the SUBSTRING function to extract the last few characters of a string, make sure the length of the string being extracted is greater than or equal to the number of characters being extracted, otherwise incorrect results may occur.