I'm trying to check if a value from a column in an oracle (10g) query is a number in order to compare it. Something like:
select case when ( is_number(myTable.id) and (myTable.id >0) )
then 'Is a number greater than 0'
else 'it is not a number'
end as valuetype
from table myTable
Any ideas on how to check that?
You can use the regular expression function 'regexp_like' in ORACLE (10g)as below:
You can use this example
Assuming that the ID column in
myTable
is not declared as a NUMBER (which seems like an odd choice and likely to be problematic), you can write a function that tries to convert the (presumably VARCHAR2) ID to a number, catches the exception, and returns a 'Y' or an 'N'. Something likeYou can then embed that call in a query, i.e.
Note that although PL/SQL has a boolean data type, SQL does not. So while you can declare a function that returns a boolean, you cannot use such a function in a SQL query.
Saish's answer using
REGEXP_LIKE
is the right idea but does not support floating numbers. This one will ...Return values that are numeric
Return values not numeric
You can test your regular expressions themselves till your heart is content at http://regexpal.com/ (but make sure you select the checkbox match at line breaks for this one).
Note that regexp or function approaches are several times slower than plain sql condition.
So some heuristic workarounds with limited applicability make sence for huge scans.
There is a solution for cases when you know for sure that non-numeric values would contain some alphabetic letters:
And if you know some letter would be always present in non-numeric cases:
When numeric cases would always contain zero:
well, you could create the is_number function to call so your code works.
EDIT: Please defer to Justin's answer. Forgot that little detail for a pure SQL call....