Databases MySQL

Remove leading and trailing spaces from a string in MySQL

It might be frustrating when trying to query for a record that, without knowing, has a leading or trailing space on a string column.

Lets say that you have a User record with ‘ ‘ as email attribute, one easy way to find this record is using the TRIM string function in MySQL:

SELECT * FROM users WHERE TRIM(email)='';

Now, to permanently remove such spaces, you can do an UPDATE on the Users table:

UPDATE users SET email=TRIM(email) WHERE email LIKE ' %;

Notice how I’m using the LIKE operand, this makes it easier to find such records.

Leave a Reply