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

前端 未结 7 1611
梦毁少年i
梦毁少年i 2020-12-30 18:58

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

相关标签:
7条回答
  • 2020-12-30 19:35
    update users
      set fullname = replace(fullname, ' ', '');
    
    0 讨论(0)
  • 2020-12-30 19:39

    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.

    0 讨论(0)
  • 2020-12-30 19:40
    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)

    0 讨论(0)
  • 2020-12-30 19:44

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

    update users set fullname = regexp_replace(fullname, '\s', '', 'g');
    commit;
    
    0 讨论(0)
  • 2020-12-30 19:51

    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"}

    0 讨论(0)
  • 2020-12-30 19:51

    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

    0 讨论(0)
提交回复
热议问题