How to select only numeric values

100,690

Solution 1

Try ISNUMERIC

SELECT *
FROM Table1
WHERE ISNUMERIC([ID]) = 1

SQLFiddle Demo

Solution 2

SELECT * FROM @Table 
WHERE Col NOT LIKE '%[^0-9]%' 

Solution 3

Just want to note that IsNumeric() has some limitations. For example all of the below will return 1.

SELECT ISNUMERIC(' - ')
SELECT ISNUMERIC(' , ')
SELECT ISNUMERIC('$')
SELECT ISNUMERIC('10.5e-1')
SELECT ISNUMERIC('$12.09')

So if you only looking to select numbers ONLY, then something like this could work:

create function [dbo].[IsNumbersOnly](@strSrc as varchar(255))
returns tinyint
as
begin

    return isnumeric(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
        @strSrc, '\', 'x'), '-', 'x'), ',', 'x'), '+', 'x'), '$', 'x'), '.', 'x'), 'e', 'x'), 'E', 'x'),
        char(9), 'x'), char(0), 'x'))
end
Share:
100,690
JetJack
Author by

JetJack

Updated on June 02, 2020

Comments

  • JetJack
    JetJack almost 4 years

    Table1

    id

    01
    wire
    02
    steve
    ram123
    03
    ....
    

    from the table1 i want to select only numeric values, It should not display alphanumeric values like (ram123)

    Expected Output

    01
    02
    03
    ....
    

    How to make a query for this condition

  • Mahmoud Gamal
    Mahmoud Gamal over 11 years
    How is that answer different from the other answer?
  • GilM
    GilM over 11 years
    Or just use WHERE ID NOT LIKE '%[^0-9]%'
  • Void Ray
    Void Ray over 11 years
    That would work too; just wanted to mention the limitations... Thanks!
  • highwingers
    highwingers over 11 years
    SELECT * FROM @Table WHERE Col NOT LIKE '%[^0-9.-]%'
  • GilM
    GilM over 11 years
    This shows that it isn't clear what "Numeric" means. From the sample data in the original question, it looks like it might be purely numeric digits (in which case this original answer is correct), or it might include other characters like "-" and ".". Maybe it means what Microsoft has implemented with ISNUMERIC, but I've never heard of anyone expecting it to meant that :-) .
  • highwingers
    highwingers over 11 years
    yes GilM, I never relied on isNumeric function in SQL or Asp Classic.
  • jatin Goyal
    jatin Goyal over 6 years
    This Query Works in Oracle