tags:

views:

110

answers:

6

I have a field (column in Oracle) called X that has values like "a1b2c3", "abc", "1ab", "123", "156"

how do I write an sql query that returns me only the X that hold pure numerical values = no letters? from the example above would be „123“ and „156“

select X from myTable where ...??

+2  A: 

The complete list of the regexp_like and other regexp functions in Oracle 11.1:

http://66.221.222.85/reference/regexp.html

In your example:

SELECT X FROM test WHERE REGEXP_LIKE(X, '^[[:digit:]]$');

Siggi
This will not work, it'll report rows that have a digit anywhere. You need to use anchors.
codaddict
I've fixed it :)
Siggi
+5  A: 

You can use the REGEXP_LIKE function as:

SELECT X 
FROM myTable 
WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');

Sample run:

SQL> SELECT X FROM SO;

X
--------------------
12c
123
abc
a12

SQL> SELECT X  FROM SO WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');

X
--------------------
123

SQL> 
codaddict
You can use regexp in Oracle 10i as well
andr
@andr: Thanks :) I tried it on a 11g box, so was not sure when did Oracle introduce regex.
codaddict
A: 

You can use following command -

LENGTH(TRIM(TRANSLATE(string1, '+-.0123456789', '')))

This will return NULL if your string1 is Numeric

your query would be -

select * from tablename 
where LENGTH(TRIM(TRANSLATE(X, '+-.0123456789', ''))) is null
Sachin Shanbhag
Cite from official SQL Reference documentation: "You cannot use an empty string for to_string to remove all characters in from_string from the return value". So you can't use empty string as the third argument in TRANSLATE(string1, '+-.0123456789', '')
andr
+2  A: 

If the only characters to consider are letters then you can do:

select X from myTable where upper(X) = lower(X)

But of course that won't filter out other characters, just letters.

Tony Andrews
+1, this is nice.
codaddict
Viet doesn't think so, hence the downvote. Or rather, he doesn't think I am nice!
Tony Andrews
A: 

If you use Oracle 10 or higher you can use regexp functions as codaddict suggested. In earlier versions translate function will help you:

select * from tablename  where translate(x, '.1234567890', '.') is null;

More info about Oracle translate function can be found here or in official documentation "SQL Reference"

UPD: If you have signs or spaces in your numbers you can add "+-" characters to the second parameter of translate function.

andr
+1  A: 

What about 1.1E10, +1, -0, etc? Parsing all possible numbers is trickier than many people think. If you want to include as many numbers are possible you should use the to_number function in a PL/SQL function. From http://www.oracle-developer.net/content/utilities/is_number.sql:

CREATE OR REPLACE FUNCTION is_number (str_in IN VARCHAR2) RETURN NUMBER IS
   n NUMBER;
BEGIN
   n := TO_NUMBER(str_in);
   RETURN 1;
EXCEPTION
   WHEN VALUE_ERROR THEN
      RETURN 0;
END;
/
jonearles
+1 best answer.
Jeffrey Kemp