Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last index of a given substring in MySQL

We can find the index of the first occurrence of a given substring in MySQL using the INSTR() function as follows.

SELECT instr('Have_a_good_day', '_') AS index_position 

It would display 5, the first occurrence of the specified substring which is in this case an underscore _.

I need to obtain the last occurrence of a given character (or a substring) something like the Java lastIndexOf(String str) method of the String class but I can't find any built-in function in MySQL.

Is there any built-in functionality to achieve this in MySQL?

like image 725
Tiny Avatar asked Oct 08 '12 04:10

Tiny


People also ask

How do you find the index at the end of a string?

The lastIndexOf() method returns the index (position) of the last occurrence of a specified value in a string. The lastIndexOf() method searches the string from the end to the beginning.

How do I find the index of a string in MySQL?

The POSITION() function returns the position of the first occurrence of a substring in a string. If the substring is not found within the original string, this function returns 0. This function performs a case-insensitive search. Note: The LOCATE() function is equal to the POSITION() function.

How do I slice a string in MySQL?

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

Is there a split function in MySQL?

MySQL Split concept comes into the picture if you are intended to split the string. In MySQL, we use SUBSTRING_INDEX() to split the string. It usually consists of three arguments i.e., string, delimiter, and position. The string value will be split based on the position.


2 Answers

@Marc B was close. In MySQL, following statement returns 12:

SELECT CHAR_LENGTH("Have_a_good_day") - LOCATE('_', REVERSE("Have_a_good_day"))+1; 

Anticipating a possible use of the value, the following statement extracts the left part of the string before the last underscore(i.e., _):

SELECT LEFT("first_middle_last", CHAR_LENGTH("first_middle_last") - LOCATE('_', REVERSE("first_middle_last"))); 

The result is "first_middle". If you want to include the delimiter, use:

SELECT LEFT("first_middle_last", CHAR_LENGTH("first_middle_last") - LOCATE('_', REVERSE("first_middle_last"))+1); 

It would be nice if they enhanced LOCATE to have an option to start the search from the right.

If you want the right part of the string after the last space a better solution is:

SELECT SUBSTRING_INDEX("first_middle_last", '_', -1); 

This returns "last".

like image 121
curt Avatar answered Sep 24 '22 15:09

curt


If you don't want the overhead of REVERSE use the following:

LEFT (    'Have_a_good_day',     LENGTH('Have_a_good_day') - LENGTH(SUBSTRING_INDEX('Have_a_good_day','_',-1))-1 ) 
like image 21
N D Avatar answered Sep 25 '22 15:09

N D