Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql like operator to get the numbers only

This is I think a simple problem but not getting the solution yet. I would like to get the valid numbers only from a column as explained here.

Lets say we have a varchar column with following values

ABC Italy Apple 234.62 2:234:43:22 France 6435.23 2 Lions 

Here the problem is to select numbers only

select * from tbl where answer like '%[0-9]%' would have done it but it returns

    234.62     2:234:43:22     6435.23     2 

Here, obviously, 2:234:43:22 is not desired as it is not valid number.

The desired result is

        234.62         6435.23         2 

Is there a way to do this?

like image 858
Thunder Avatar asked Jan 09 '10 07:01

Thunder


People also ask

Can SQL like be used for numbers?

No, you can't use LIKE for numeric fields. Try using < , > or = , >= , <= ;) If you want to search in a numeric field for things like "beginning with 12" or sth like this, your design not fits your needs.

What does like %% mean in SQL?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.


2 Answers

You can use the following to only include valid characters:

SQL

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

Results

Col --------- 234.62 6435.23 2 
like image 141
beach Avatar answered Sep 28 '22 00:09

beach


You can try this

ISNUMERIC (Transact-SQL)

ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.

DECLARE @Table TABLE(         Col VARCHAR(50) )  INSERT INTO @Table SELECT 'ABC'  INSERT INTO @Table SELECT 'Italy'  INSERT INTO @Table SELECT 'Apple'  INSERT INTO @Table SELECT '234.62'  INSERT INTO @Table SELECT '2:234:43:22'  INSERT INTO @Table SELECT 'France'  INSERT INTO @Table SELECT '6435.23' INSERT INTO @Table SELECT '2'  INSERT INTO @Table SELECT 'Lions'  SELECT  * FROM    @Table WHERE   ISNUMERIC(Col) = 1 
like image 42
Adriaan Stander Avatar answered Sep 27 '22 23:09

Adriaan Stander