Thursday, April 2, 2009

Distinguishing numbers from strings in a String(varchar) coulmn.

Have you ever come across a need to filter out numbers(or number like) that are stored in a column along with string values?

e.g. Let us say myTable.myColumn of type varchar(50) has the following values.
    EA-234
    1234567
    CT/234
    9876543
    10203040
    AB/04/02/09


and you want to select only the rows that have "1234567, 9876543 and 10203040".
The following query is very consise and efficient than building a "like" search for all allowed prefixes.

select * from myTable
where myColumn between '0' and 'A'
and myColumn not like 'A%'


Remember that the ranges are inclusive in a "between" clause, so you may have to eliminate all the values begining with "A". One may be able to use a different filter such as "and len(myColumn) = 7" or rewrite the where clause as
myColumn >= '0' and < 'A' to achieve it instead of "not like" depending on actual data.

Note: It may noted that "9" cannot be used in the above query instead of "A" because the filter will not include values such as "99" or "921" etc.

No comments: