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?
How is the column defined? If its a varchar field, then its not a number (or stored as one). Oracle may be able to do the conversion for you (eg, select * from someTable where charField = 0), but it will only return rows where the conversion holds true and is possible. This is also far from ideal situation performance wise.
So, if you want to do number comparisons and treat this column as a number, perhaps it should be defined as a number?
That said, here's what you might do:
You might also include the other parameters that the regular to_number has. Use as so:
It won't return any rows that Oracle sees as an invalid number.
Cheers.
One additional idea, mentioned here is to use a regular expression to check:
The nice part is you do not need a separate PL/SQL function. The potentially problematic part is that a regular expression may not be the most efficient method for a large number of rows.
Please note that it won't consider 45e4 as a number, But you can always change regex to accomplish the opposite.
Here's a simple method which :
Result:
Granted this might not be the most powerful method of all; for example ".," is falsely identified as a numeric. However it is quite simple and fast and it might very well do the job, depending on the actual data values that need to be processed.
For integers, we can simplify the Translate operation as follows :
How it works
From the above, note the
Translate
function's syntax isTRANSLATE(string, from_string, to_string)
. Now theTranslate
function cannot acceptNULL
as theto_string
argument. So by specifying'a0123456789'
as thefrom_string
and'a'
as theto_string
, two things happen:a
is left alone;0
to9
are replaced with nothing since no replacement is specified for them in theto_string
.In effect the numbers are discarded. If the result of that operation is
NULL
it means it was purely numbers to begin with.