How do I remove all spaces from a field in a Postgres database in an update query?

Postgresql

Postgresql Problem Overview


What would be the proper syntax used to run an update query on a table to remove all spaces from the values in a column?

My table is called users and in the column fullname some values look like 'Adam Noel'. I want to remove the space so that the new value is 'AdamNoel'

I have like 30k rows

Postgresql Solutions


Solution 1 - Postgresql

update users
  set fullname = replace(fullname, ' ', '');

Solution 2 - Postgresql

To remove all whitespace (not just space characters) one can use:

update users set fullname = regexp_replace(fullname, '\s', '', 'g');
commit;

Solution 3 - Postgresql

Just use the simple code

 REPLACE('some_string', ' ', '')

or

Replace('some_string', '\s', '')

to remove any white space from the string

Solution 4 - Postgresql

You can include a condition to update only values that need it with the replace.

UPDATE users SET fullname = REPLACE(fullname, ' ', '') WHERE fullname ~* ' ';

Quick and dirty

Solution 5 - Postgresql

If it's a text[] column, you can do something like this:

UPDATE users SET pets = string_to_array(replace(array_to_string(pets, ';'), ' ', ''), ';');

Before: {"Big Dog", "Small Cat"}

After: {"BigDog", "SmallCat"}

Solution 6 - Postgresql

Can perform an update all with the trim function.

UPDATE users AS u SET name = TRIM(u.name)

Optionally add a clause to update only the records that need it, instead of all, but uses more CPU.

UPDATE users AS u SET name = TRIM(u.name) WHERE LENGTH(TRIM(u.name)) <> LENGTH(u.name)

If the table has a unique index on the value being trimmed, you could get a duplicate key error.

Solution 7 - Postgresql

UPDATE customers SET first_name = TRIM (TRAILING FROM first_name ) where id = 1

For example, if you want to remove spaces from the beginning of a string, you use the following syntax:

TRIM(LEADING FROM string) The following syntax of the TRIM() function removes all spaces from the end of a string.

TRIM(TRAILING FROM string) And to remove all spaces at the beginning and ending of a string, you use the following syntax:

TRIM(BOTH FROM string)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeoSamView Question on Stackoverflow
Solution 1 - Postgresqla_horse_with_no_nameView Answer on Stackoverflow
Solution 2 - PostgresqlRasjid WilcoxView Answer on Stackoverflow
Solution 3 - PostgresqlBassam FaramawiView Answer on Stackoverflow
Solution 4 - PostgresqlGudmoView Answer on Stackoverflow
Solution 5 - PostgresqlWesty92View Answer on Stackoverflow
Solution 6 - PostgresqlDennisView Answer on Stackoverflow
Solution 7 - PostgresqlvipinlalrvView Answer on Stackoverflow