I have a table containing a list of name which might contain special character:
id name
1 Johän
2 Jürgen
3 Janna
4 Üdyr
...
Is there a function that replaces each character for another specific one? (Not necessarily an unaccented one). Something like this:
SELECT id, function('ä,ü',name,'ae,ue');
Result:
id name
1 Johaen
2 Juergen
3 Janna
4 UEdyr
...
replace()
If you want just to replace one or few characters you can use function replace(string text, from text, to text) that replaces all occurrences in string substring. The replace function can be used to replace one character to several characters.
translate()
If you want to translate some letters to other letters you can user function translate(string text, from text, to text) that replaces any character in a string that matches a character in the from by the corresponding character in the to set.
Some data to play with:
drop table if exists xyz;
create table xyz (
id serial not null,
name varchar(30)
);
insert into xyz (name) values
('Juhänäo'),
('Jürgüen'),
('Dannäu'),
('Übüdyr');
Example of replace function:
select replace(name, 'ä', 'a') from xyz;
This function replaces letter ä in the name column with letter a. Juhänäo becomes Juhanao.
select replace(name, 'ä', 'ae') from xyz;
Now it replaces letter ä with ae.
select replace(replace(replace(name, 'ä', 'ae'), 'ü', 'ue'), 'Ü', 'Ue') from xyz;
Not very nice, but in the example all ä become ae, ü become ue, and Ü become 'Ue'.
update xyz set name = replace(replace(replace(name, 'ä', 'ae'), 'ü', 'ue'), 'Ü', 'Ue');
Changes letters and updates rows. The result of the update is following:
Juhaenaeo
Juergueen
Dannaeu
Uebuedyr
Example of translate function:
select translate(name, 'ä,ü,Ü', 'a,u,U') from xyz;
Translates all letters ä to a, ü to u and Ü to U.
update xyz set name = translate(name, 'ä,ü,Ü', 'a,u,U');
Updates table so all predefined letters are translated and the change is saved to the database. The result of the update is following:
Juhanao
Jurguen
Dannau
Ubudyr
More information:
Replace characters with multi-character strings
Postgresql string functions
If you are after German letters, then this works:
CREATE OR REPLACE FUNCTION public.udf_transliterate_german(
german_word character varying)
RETURNS character varying
LANGUAGE 'sql'
COST 100
VOLATILE PARALLEL UNSAFE
AS $BODY$
SELECT REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(
REPLACE(german_word,
'ä','ae'),
'ö','oe' ),
'ü','ue'),
'ß','ss'),
'Ä', 'AE'),
'Ö', 'OE'),
'Ü', 'UE'),
'ẞ', 'SS');
$BODY$;
It is not elegant though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With