Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get everything before the last occurrence of a character in MySQL?

Tags:

sql

mysql

I want to get everything before the last occurrence of a specific character from a column.

SUBSTRING_INDEX with negative value works well for the separation but return the part of the string I want to delete. For example, consider a column as

first. second. third. fourth

SUBSTRING_INDEX(Col1, '.', -1) returns fourth, but I want to get

first. second. third.

In fact, I want to update the same col by removing anything after the last occurrence of .. In other words, I want to remove SUBSTRING_INDEX(Col1, '.', -1) part, but I cannot simply use REPLACE as

UPDATE table1 SET Col1=REPLACE(Col1,SUBSTRING_INDEX(Col1, '.', -1),'')

because it may occur in other parts of the string.

like image 923
Googlebot Avatar asked Feb 22 '19 06:02

Googlebot


People also ask

How do I get all the items left of a character in SQL?

SQL Server LEFT() Function The LEFT() function extracts a number of characters from a string (starting from left).

How do you find the occurrence of a character in a string in MySQL?

MySQL LOCATE() Function The LOCATE() 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.

How do I select a substring in SQL after a specific character?

To find the index of the specific character, you can use the CHARINDEX(character, column) function where character is the specific character at which you'd like to start the substring (here, @ ). The argument column is the column from which you'd like to retrieve the substring; it can also be a literal string.

How do I delete everything after a character in MySQL?

In order to delete everything after a space, you need to use SUBSTRING_INDEX().


3 Answers

Here is one trick do this, making use of the REVERSE function:

UPDATE yourTable
SET col =
    REVERSE(SUBSTRING(REVERSE(col), INSTR(REVERSE(col), '.')))

Demo

The idea here is to reverse the string, then use INSTR to find the position of the last (now first) dot. Then, we substring from the position to the beginning, and then reverse again.

like image 118
Tim Biegeleisen Avatar answered Sep 22 '22 12:09

Tim Biegeleisen


I wouldn't use reverse(). Instead:

UPDATE table1
    SET Col1 = LEFT(col1, LENGTH(col1) - LENGTH(SUBSTRING_INDEX(Col1, '.', -1)) - 1);
like image 32
Gordon Linoff Avatar answered Sep 21 '22 12:09

Gordon Linoff


YOu can use left() and locate() funtion

DEMO

UPDATE table1 SET Col1= left(col1,
locate(SUBSTRING_INDEX(col1, '.', -1),col1))

OUTPUT:

val
first. second. third. 
like image 45
Fahmi Avatar answered Sep 21 '22 12:09

Fahmi