How to remove leading and trailing whitespace in a MySQL field?
A general answer that I composed from your answers and from other links and it worked for me and I wrote it in a comment is:
UPDATE FOO set FIELD2 = TRIM(Replace(Replace(Replace(FIELD2,'\t',''),'\n',''),'\r',''));
etc.
Because trim() doesn't remove all the white spaces so it's better to replace all the white spaces u want and than trim it.
Hope I could help you with sharing my answer :)
You're looking for TRIM.
UPDATE FOO set FIELD2 = TRIM(FIELD2);
Seems like it might be worth it to mention that TRIM can support multiple types of whitespace, but only one at a time and it will use a space by default. You can, however, nest TRIM
s.
TRIM(BOTH ' ' FROM TRIM(BOTH '\n' FROM column))
If you really want to get rid of all the whitespace in one call, you're better off using REGEXP_REPLACE
along with the [[:space:]]
notation. Here is an example:
SELECT
-- using concat to show that the whitespace is actually removed.
CONCAT(
'+',
REGEXP_REPLACE(
' ha ppy ',
-- This regexp matches 1 or more spaces at the beginning with ^[[:space:]]+
-- And 1 or more spaces at the end with [[:space:]]+$
-- By grouping them with `()` and splitting them with the `|`
-- we match all of the expected values.
'(^[[:space:]]+|[[:space:]]+$)',
-- Replace the above with nothing
''
),
'+')
as my_example;
-- outputs +ha ppy+