TRANSLATE() gotcha

TRANSLATE() is the PL/SQL function that provides the same functionality as CHRTRAN() in Visual FoxPro. The function searches the first string and replaces every character in the second one with the corresponding value from the third string:

SELECT TRANSLATE('12341234','23','XZ') FROM DUAL;



1XZ41XZ4


Like CHRTRAN in Visual FoxPro you can use TRANSLATE() to remove characters from a string. When the third string is shorter than the second one, all characters in the second string that do not have a corresponding position in the third string are removed. There's a major difference to Visual FoxPro, though:


SELECT TRANSLATE('12345','24','') FROM DUAL


You might expect this expression to return '135'. However, Oracle returns NULL. How comes that? Oracle doesn't support empty strings. Empty strings, like the third parameter, automatically become NULL in Oracle. Yet, if any of the parameters for TRANSLATE() is NULL, so is the result. To get around this issue, you can use the same trick we used with IF lines in DOS batch files years ago:


SELECT TRANSLATE('12345','.24','.') FROM DUAL


This expression replaces periods with periods and removes '2' and '4'. By adding an additional character the third parameter doesn't become NULL and you get the result you expect.