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.
SQL Server LEFT() Function The LEFT() function extracts a number of characters from a string (starting from left).
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.
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.
In order to delete everything after a space, you need to use SUBSTRING_INDEX().
Here is one trick do this, making use of the REVERSE
function:
UPDATE yourTable
SET col =
REVERSE(SUBSTRING(REVERSE(col), INSTR(REVERSE(col), '.')))
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.
I wouldn't use reverse()
. Instead:
UPDATE table1
SET Col1 = LEFT(col1, LENGTH(col1) - LENGTH(SUBSTRING_INDEX(Col1, '.', -1)) - 1);
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.
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