Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql: substring that returns the first occurrence from the right? (subrstring?!)

Tags:

mysql

is there a way to return the first occurrence of a space from the right side of the string in sql?

like image 952
ufk Avatar asked Jan 13 '10 12:01

ufk


People also ask

Which MySQL function will return the position of the first occurence of a substring in a string?

The LOCATE() function returns the position of the first occurrence of a substring in a string.

How do I get the first letter of a string in MySQL?

To fetch the first alphabet from the strings, use LEFT(). This method allows you to return characters from the left of the string.

How do I slice a string in MySQL?

The SUBSTRING() function extracts a substring from a string (starting at any position). Note: The SUBSTR() and MID() functions equals to the SUBSTRING() function.

What is returned by Instr (' Hello World w ')?

The INSTR() function returns the position of the first occurrence of a string in another string.


3 Answers

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)
like image 133
YOU Avatar answered Nov 11 '22 12:11

YOU


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`))
like image 33
nickf Avatar answered Nov 11 '22 11:11

nickf


You could use REVERSE in conjunction with INSTR.

i.e.

select right('12345 67 8', instr(reverse('12345 67 8'), ' '));

returns '8'.

like image 40
davek Avatar answered Nov 11 '22 12:11

davek