Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove part of string in mysql?

Tags:

mysql

In one table of my database I have strings which looks like this one:

sometext-othertext

How to remove the text including dash with SELECT statement so the result to be just sometext?

like image 615
jingo Avatar asked Sep 20 '11 07:09

jingo


People also ask

How do I remove a specific part of a string in SQL?

SQL Server TRIM() Function The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string.

How do I remove part of a string?

We can remove part of the string using REPLACE() function. We can use this function if we know the exact character of the string to remove. REMOVE(): This function replaces all occurrences of a substring within a new substring.

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.


2 Answers

Return the substring before the first occurrence of the delimiter "-":

SELECT SUBSTRING_INDEX('foo-bar-bar', '-', 1) as result;

Outputs result = "foo"

You can replace 1 with the numbers of occurrences you want before getting the substring

SELECT SUBSTRING_INDEX('foo-bar-bar', '-', 2) as result;

Outputs result = "foo-bar"

Reference: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index

like image 134
Bluewind Avatar answered Oct 06 '22 00:10

Bluewind


SELECT REPLACE("sometext-othertext","-", "") as newvalue

This should do it.
Edit:

  SELECT SUBSTRING_INDEX('sometext-othertext', '-', 1) as newvalue;

apologies for not understanding the question earlier.

like image 30
zarun Avatar answered Oct 06 '22 00:10

zarun