MySQL trim() not removing space inside a string - mysql

Given the value of name column: AL TAIRAWI TRADING ESTABLISHMENT
Update ae_companies set uniqueidentifier = CONCAT(trim(LEFT(name, 5)), '_', id, '_ae')
Above query produces this:
AL TA_6_ae
What I am looking for is this:
ALTA_6_ae
I have no idea why the trim() isn't working here.

Use replace() instead of trim().
Update ae_companies
set uniqueidentifier = CONCAT(replace(LEFT(name, 5), ' ', ''), '_', id, '_ae')
TRIM() isn't working (doing the job you thought it does) in your case because its description is:
Remove leading and trailing spaces
When you do LEFT(name, 5) which produces AL TA all leading and trailing spaces are removed when you wrap this around TRIM() the way you did. In your case space character is neither at the last nor at the first position, so this is why your result doesn't change when trimmed.
What you're looking for is a REPLACE($INPUT_STRING, ' ', '') to truncate all occurences of space character within the input string.

Related

removing whitespaces not working MySQL. Used TRIM() and REPLACE()

Take a look : FIDDLE
select IF((TRIM(replace(' IKECHUKWU OSUJI',' ',''))=TRIM(replace('IKECHUKWU OSUJI','
',''))),"same","diff");
select IF((TRIM(replace(' Aman Minhas ',' ',''))=TRIM(replace(' Aman Min has','
',''))),"same","diff");
The first query returns diff. The second returns same. Its some weird spacing issue, cant seem to understand why this behaviour.
Your first string has a tab in it:
select IF((TRIM(replace(' IKECHUKWU OSUJI',' ',''))
^ this is actually a tab in the Fiddle
You can get rid of it with an additional REPLACE:
REPLACE(REPLACE(myString, ' ', ''), '\t', '')
The \t is a special literal. Other special literals such as newline or ASCII NUL may impact you as well. Literals are listed here.

SQL - Remove Parenthesis from Phone Number

I'm trying to remove parenthesis from the area code of a number. I'm able to do so but when I try to concatenate the two Replace functions, the numbers repeat with only one parenthesis removed.
This is what I tried so far:
SELECT HomePhone, REPLACE(HomePhone, '(', '') +
REPLACE(HomePhone, ')', '') AS Expr1
FROM dbo.Employees
http://i.imgur.com/4iJoFzE.png
Nest don't add
Replace(Replace(HomePhone,')',''),'(','')
Look at how the function replace works. It expects string With Text To Evaluate, string to replace, string to replace with)
By adding them you should be getting the number listed twice, but if the data type isn't long enough it may be truncating values. by nesting you're telling the system to replace the ) and then use that string w/o the ) to have the ( replaced with ''.
You cannot concatenate in this way, you must use the concat function in SQL. Or use thus:
SELECT HomePhone, REPLACE(REPLACE(HomePhone, ')', ''), '(', '') AS Expr1 FROM dbo.Employees

Using COALESCE in MySQL

I'm just getting used to MySQL, I've come from a SQL Server background...
This SQL query builds an address how it should in SQL Server, how can I adapt it to use within MySQL. When I run it in SQL Server it displays all the data within each field, when run in MySQL it just shows me the first field.
Why would this be, what should I do different in MySQL?
SELECT COALESCE(House, '') + ' ' + COALESCE(StreetName, '') + ' ' + COALESCE(TownCity, '') + ' ' + COALESCE(Postcode, '') AS Display
FROM MyTable
WHERE Postcode LIKE '%A1 2AB%'
Use the concat() function:
SELECT concat(COALESCE(House, ''), ' ', COALESCE(StreetName, ''), ' ',
COALESCE(TownCity, ''), ' ', COALESCE(Postcode, '')
) AS Display
FROM MyTable
WHERE Postcode LIKE '%A1 2AB%';
You can also do this with concat_ws(). This eliminates the need for all the spaces:
SELECT concat_ws(COALESCE(House, ''), COALESCE(StreetName, ''),
COALESCE(TownCity, ''), COALESCE(Postcode, '')
) AS Display
FROM MyTable
WHERE Postcode LIKE '%A1 2AB%';
What happens in MySQL is that the + does just what you expect: it adds numbers. A string that contains a number is converted to a number automatically, with silent errors for strings that have no numbers. In practice, this means that a string that starts with a non-digit (and non-decimal point) is converted to a 0.
So, house, which presumably usually numeric, is converted to a number just fine. All the other strings are converted to numbers but become zero and the house number is not changed. You would have gotten much different results if your post codes were American-style zip codes (which are typically numeric).
EDIT:
As #fthiella points out, the coalesce() is not necessary for concat_ws(). The two statements would do different things, because NULLs in the original query result in repeated separators. NULLs in the concat_ws() version would have only a single separator (which might be desirable).
However, I would tend to keep the coalesce() anyway. The behavior of concat() and concat_ws() varies in this regard. concat() returns NULL if any of its arguments is NULL. concat_ws() skips NULL arguments after the initial separator. Who can remember that distinction? It sounds like a recipe for confusion in production code. So, I would also use coalesce() even though it is optional.

Can not use substr function in MySQL to get left part of the string using last occurrence of delimiter

I have a question to worm up your minds :)
I need to extract a string A from string B where B is stored in MySQL table.
This is string B:
#/schema#/CT[Items]#/sequence[0]#/element[item]#/CT[]#/sequence[0]#/element[productImage]
And this is A:
#/schema#/CT[Items]#/sequence[0]#/element[item]#/CT[]#/sequence[0]
The delimiter in my case is '#' and I need to remove it along with the following characters '/element[productImage]'.
I tried different functions like SUBSTR(str, pos, len), POSITION(substr IN str), and REVERSE(str) but cannot solve the problem.
Note that index of the last occurrence of '#' is unknown. And I can not find a way to locate the last index of the '#' character (like lastIndexOf() function in JAVA).
I believe that there is a way to do it by reversing the whole string first, cutting the unnecessary part then reversing again to get the desired result.
Can any one help please.
Try this:
LEFT(str, CHAR_LENGTH(str) - LOCATE('#', REVERSE(str)))
You could count the number of occurrences with:
CHAR_LENGTH(stringB)-CHAR_LENGTH(REPLACE(stringB, '#', ''))
and then you can just use SUBSTRING_INDEX:
SELECT
SUBSTRING_INDEX(
stringB,
'#',
CHAR_LENGTH(stringB)-CHAR_LENGTH(REPLACE(stringB, '#', '')))
This looks like it works
SELECT TRIM(TRAILING CONCAT("#", SUBSTRING_INDEX(str, '#', -1)) FROM str)
This part :
SUBSTRING_INDEX(str, '#', -1)
grabs everything after the last token occurrence without the token
this bit :
TRIM(TRAILING 'x' FROM str)
returns the string with the last occurrence of 'x' (or whatever string provided) from the target string.
But since SUBSTRING_INDEX returns the substring without the delimiter token, you need to trim off the trailing token as well, for which we use the CONCAT to add it back to the front of the "bad" sub-string.

Replacing substrings in MySQL

I have some sentences in string in MySQL. And I need to replace substrings such as 'My' to 'my' if this word not first in sentence. How I can doing this?
CHAR, REPLACE, REPEAT, etc. I'd recommend reading mySQL ref: http://dev.mysql.com/doc/refman/5.5/en/string-functions.html
If you just want to replace several words, you can replace them, using this approach:
UPDATE str_test SET str = REPLACE(str, ' My', ' my')
fiddle
As the words inside the text will be preceded by space. But if you want a regexp replace, it will be a more difficult task:
How to count words in MySQL / regular expression replacer?
https://dba.stackexchange.com/questions/15250/how-to-do-a-case-sensitive-search-in-where-clause
MySql support for string is very limited. A quick solution would be to use something like this:
SELECT
CONCAT(
LEFT(col, 1),
REPLACE(SUBSTRING(col, 2), 'My', 'my')
)
Please see fiddle here. This will replace all the strings My to my, except the first one.
Or maybe this:
SELECT
col,
RTRIM(REPLACE(CONCAT(col, ' '), ' My ', ' my '))
FROM
yourtable
that will replace all whole words except the first one.