Oracle/PLSQL: Test a string for an alphanumeric value
Question: In Oracle, I want to know if a string value contains alphanumeric characters only. How can I do this?
Answer: To test a string for alphanumeric characters, you could use a combination of the LENGTH, TRIM, AND TRANSLATE functions built into Oracle.
You can use the following command:
LENGTH(TRIM(TRANSLATE(string1, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-.0123456789', ' ')))
string1 is the string value that you are testing
This function will return a null value if string1 is alphanumeric. It will return a value "greater than 0" if string1 contains any non-alphanumeric characters.
For example,
LENGTH(TRIM(TRANSLATE('Tech on the Net!!!', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-.0123456789', ' '))) would return 3 LENGTH(TRIM(TRANSLATE('Tech1Net2^', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-.0123456789', ' '))) would return 1 LENGTH(TRIM(TRANSLATE('Tech on the Net567', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+-.0123456789', ' '))) would return null
Learn more about the translate function.
Learn more about the length function.
Learn more about the trim function.