is there a way to return the first occurrence of a space from the right side of the string in sql?
The LOCATE() function returns the position of the first occurrence of a substring in a string.
To fetch the first alphabet from the strings, use LEFT(). This method allows you to return characters from the left of the string.
The SUBSTRING() function extracts a substring from a string (starting at any position). Note: The SUBSTR() and MID() functions equals to the SUBSTRING() function.
The INSTR() function returns the position of the first occurrence of a string in another string.
I think you are looking for something like SUBSTRING_INDEX
mysql> SELECT SUBSTRING_INDEX('first second end', ' ', -1);
+----------------------------------------------+
| SUBSTRING_INDEX('first second end', ' ', -1) |
+----------------------------------------------+
| end |
+----------------------------------------------+
1 row in set (0.00 sec)
Hmm, a brief browse through the function list didn't pop up any "search backwards" functions at me, but what you could do is reverse the string and search forwards:
SELECT LENGTH(`haystack`) - POSITION('needle' IN REVERSE(`haystack`))
You could use REVERSE in conjunction with INSTR.
i.e.
select right('12345 67 8', instr(reverse('12345 67 8'), ' '));
returns '8'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With