If there is a short, static list of possible special characters, translate()
is typically much faster:
test=> SELECT translate('ABC%$! DEF*& GHI', ' %$!*&', '_');
translate
-------------
ABC_DEF_GHI
Every listed character with no replacement is removed.
Else, consider Adam's answer.
But I suppose you wouldn't want leading or trailing _
in the result? May surface after removing noise characters. So feed the result to trim()
:
test=> SELECT translate('ABC%$! DEF*& GHI %', ' %$!*&', '_')
test-> , trim(translate('ABC%$! DEF*& GHI %', ' %$!*&', '_'), '_');
translate | btrim
--------------+-------------
ABC_DEF_GHI_ | ABC_DEF_GHI