How to make to_number ignore non-numerical values - sql

Column xy of type 'nvarchar2(40)' in table ABC.
Column consists mainly of numerical Strings
how can I make a
select to_number(trim(xy)) from ABC
query, that ignores non-numerical strings?

In general in relational databases, the order of evaluation is not defined, so it is possible that the select functions are called before the where clause filters the data. I know this is the case in SQL Server. Here is a post that suggests that the same can happen in Oracle.
The case statement, however, does cascade, so it is evaluated in order. For that reason, I prefer:
select (case when NOT regexp_like(xy,'[^[:digit:]]') then to_number(xy)
end)
from ABC;
This will return NULL for values that are not numbers.

You could use regexp_like to find out if it is a number (with/without plus/minus sign, decimal separator followed by at least one digit, thousand separators in the correct places if any) and use it like this:
SELECT TO_NUMBER( CASE WHEN regexp_like(xy,'.....') THEN xy ELSE NULL END )
FROM ABC;
However, as the built-in function TO_NUMBER is not able to deal with all numbers (it fails at least when a number contains thousand separators), I would suggest to write a PL/SQL function TO_NUMBER_OR_DEFAULT(numberstring, defaultnumber) to do what you want.
EDIT: You may want to read my answer on using regexp_like to determine if a string contains a number here: https://stackoverflow.com/a/21235443/2270762.

You can add WHERE
SELECT TO_NUMBER(TRIM(xy)) FROM ABC WHERE REGEXP_INSTR(email, '[A-Za-z]') = 0
The WHERE is ignoring columns with letters. See the documentation

Related

SQL Like and Wildcard with Oracle SQL Developer

I am using SQL Developer over a backend Oracle DB. I have a record where the buyer name is Pete Hansen.
Why I try
select * from data1 where buyer = 'Pete Hansen';
I get the result, no problem. However, when I use the following, I do not get any results:
select * from data1 where buyer like 'Pete Hansen';
Also, when I try the following, I do not get any results
select * from data1 where buyer like 'Pete Hans_n';
but the following works well:
select * from data1 where buyer like 'Pete Hans_n%';
Could you please help me understand? Thanks in advance.
Your buyer column seems to be defined as char; you can see the issue reproduced in this db<>fiddle, but not when the column is varchar2.
The documentation for character comparison explains the difference between blank-padded or nonpadded comparison semantics. When you compare them with =, because both the column and the string literal are `char, blank-padded semantics are used:
With blank-padded semantics, if the two values have different lengths, then Oracle first adds blanks to the end of the shorter one so their lengths are equal. ... If two values have no differing characters, then they are considered equal. This rule means that two values are equal if they differ only in the number of trailing blanks. Oracle uses blank-padded comparison semantics only when both values in the comparison are either expressions of data type CHAR, NCHAR, text literals, or values returned by the USER function.
When the column is `varchar2 then nonpadded semantics are used:
With nonpadded semantics, ... If two values of equal length have no differing characters, then the values are considered equal. Oracle uses nonpadded comparison semantics whenever one or both values in the comparison have the data type VARCHAR2 or NVARCHAR2.
LIKE works differently. Only your final pattern with % matches, because that is allowing for the trailing spaces in the char value, while the other two patterns do not. With the varchar2 version there aren't any trailing spaces to the other two patterns also match.
It's unusual to need or want to user char columns; varchar2 is more usual. Tom Kyte opined on this many years ago.
I suspect it may have to do with trailing white spaces, which like operator is not forgiving about but = is. To test that, try
select * from data1 where trim(buyer) like 'Pete Hansen';

Sql Oracle query - field contains special characters or alpha

need to see if a taxid field contains letters or any special characters:. *,!,?,#,#,$,&,+,(,),/
How can I write this SQL?
Oracle has regexp_like:
select * from tablename where regexp_like(columnname, '[*!?##$&+()/]');
Here is the best way to display all the taxid's that are NOT entirely composed of digits:
select taxid
from your_table
where translate(taxid, '.0123456789', '.') is not null
TRANSLATE will "translate" (replace) each period in the input with a period in the output. Since the other characters in the second argument do not have a corresponding character in the third argument, they will simply be deleted. If the result of this operation is not null, then the taxid contains at least one character that is not a digit. If taxid is all digits, the result of the operation is null. Note that the period character used here is needed, due to an oddity in Oracle's definition of TRANSLATE: if any of its arguments is null, then so is its return value. That doesn't make a lot of sense, but we must work with the functions as Oracle defined them.

Oracle SQL: Replace all non-numeric values, such as NULL, blank or empty strings

I have a column that is formatted as number but seems to contain some other values as well that are causing trouble with my other functions (Rtrim, Xmlagg, Xmlelement, Extract), leading the whole query to fail (which works well if I take this column out).
Can someone tell me the best way to replace anything in a column that is not a valid number by 0 (or alternatively a placeholder number like 99999) ?
I tried the following but guess this only covers NULL values, not empty strings or blank strings which I think I have to replace first.
TO_CHAR(NVL(a.mycolumn, 0))
Many thanks in advance,
Mike
In Oracle, you should be able to use TRIM():
NVL(TRIM(a.mycolumn), '0')
Oracle (by default) treats empty strings as NULL.
Do note that this will trim the result, even if it is not NULL. If that is not desirable, use CASE:
(CASE WHEN TRIM(a.mycolumn) IS NULL THEN '0' ELSE a.myolumn END)
Use REGEXP_LIKE
For Numeric:
REGEXP_LIKE (numeric_value, '^\d+(\.\d+)?$')
or with null
REGEXP_LIKE(NVL(value, 'NULL'), '^\d+(\.\d+)?$|NULL$')

SQLite TRIM same character, multiple columns

I have a table in an SQLite db which has multiple columns with leading '='. I understand that I can use...
SELECT TRIM(`column1`, '=') FROM table;
to clean one column however I get a syntax error if I try for example, this...
SELECT TRIM(`column1`, `column2`, `column3`, '=') FROM table;
Due to incorrect number of arguments.
Is there a more efficient way of writing this code than applying the trim to each column separately like this?
SELECT TRIM(`column1`,'=')as `col1`, TRIM(`column2`,'=')as `col2`, TRIM(`column3`,'=')as `col3` FROM table;
How SQLite guide tells:
trim(X,Y)
The trim(X,Y) function returns a string formed by removing any and all
characters that appear in Y from both ends of X. If the Y argument is
omitted, trim(X) removes spaces from both ends of X.
You have only two parameters, so it's impossible apply it one shot on 3 columns table.
The first parameter is a column, or variable on you can apply trim. The second parameter is a character to change.

SQL: insert space before numbers in string

I have a nvarchar field in my table, which contains all sorts of strings.
In case there are strings which contain a number following a non-number sign, I want to insert a space before that number.
That is - if a certain entry in that field is abc123, it should be turned into abc 123, or ab12.34 should become ab 12. 34.I want this to be done throughout the entire table.
What's the best way to achieve it?
You can try something like that:
select left(col,PATINDEX('%[0-9]%',col)-1 )+space(1)+
case
when PATINDEX('%[.]%',col)<>0
then substring(col,PATINDEX('%[0-9]%',col),len(col)+1-PATINDEX('%[.]%',col))
+space(1)+
substring(col,PATINDEX('%[.]%',col)+1,len(col)+1-PATINDEX('%[.]%',col))
else substring(col,PATINDEX('%[0-9]%',col),len(col)+1-PATINDEX('%[0-9]%',col))
end
from tab
It's not simply, but I hope it will help you.
SQL Fiddle
I used functions (link to MSDN):
LEFT, PATINDEX, SPACE, SUBSTRING, LEN
and regular expression.