The SUBSTR() function in MySQL is used to extract a substring from a given string. It allows you to return a part of the string starting from a specified position, and optionally, you can specify the length of the substring.
Syntax:
SUBSTR(string, start_position, length)
- string: The input string from which the substring is to be extracted.
- start_position: The position from which the substring extraction starts. The position is 1-based, meaning the first character is at position 1.
- length (optional): The number of characters to extract. If this is omitted, it will return the substring from the start position to the end of the string.
Examples:
-
Extracting a substring from a string:
SELECT SUBSTR('Hello, World!', 8, 5);Result:
'World'Explanation: This extracts 5 characters starting from position 8 (the letter "W"). -
Extracting substring with no length specified:
SELECT SUBSTR('Hello, World!', 8);Result:
'World!'Explanation: This extracts all characters from position 8 to the end of the string. -
Using negative start_position:
SELECT SUBSTR('Hello, World!', -6, 5);Result:
'World'Explanation: If you use a negative number forstart_position, MySQL starts counting from the end of the string. Here, it starts 6 characters from the end of the string. -
Extracting from the beginning of a string:
SELECT SUBSTR('Hello, World!', 1, 5);Result:
'Hello'Explanation: This extracts the first 5 characters from the string.
Notes:
- If the
start_positionexceeds the length of the string, MySQL will return an empty string. - If
lengthis negative, MySQL will return the substring starting from thestart_positionand extending in reverse.
Let me know if you'd like further examples or clarification!
No comments:
Post a Comment