tags:

views:

365

answers:

2

Does mysql have a funcion like is_num() which can allow me determine the data is numeric or not?

Thanks.

+1  A: 

You may want to create a user defined function that matches the value against a regular expression:

CREATE FUNCTION IsNumeric (sIn varchar(1024)) RETURNS tinyint 
   RETURN sIn REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$'; 

Source: MySQL Forums :: Microsoft SQL Server :: IsNumeric() clause in MySQL?


Truthy Tests:

mysql> SELECT ISNUMERIC('1');
+----------------+
| ISNUMERIC('1') |
+----------------+
|              1 |
+----------------+
1 row in set (0.01 sec)

mysql> SELECT ISNUMERIC(25);
+---------------+
| ISNUMERIC(25) |
+---------------+
|             1 |
+---------------+
1 row in set (0.00 sec)

mysql> SELECT ISNUMERIC('-100');
+-----------------+
| ISNUMERIC(-100) |
+-----------------+
|               1 |
+-----------------+
1 row in set (0.03 sec)

mysql> SELECT ISNUMERIC('1.5');
+------------------+
| ISNUMERIC('1.5') |
+------------------+
|                1 |
+------------------+
1 row in set (0.00 sec)

mysql> SELECT ISNUMERIC('-1.5');
+-------------------+
| ISNUMERIC('-1.5') |
+-------------------+
|                 1 |
+-------------------+
1 row in set (0.02 sec)

Falsy Tests:

mysql> SELECT ISNUMERIC('a');
+----------------+
| ISNUMERIC('a') |
+----------------+
|              0 |
+----------------+
1 row in set (0.02 sec)

mysql> SELECT ISNUMERIC('a1');
+-----------------+
| ISNUMERIC('a1') |
+-----------------+
|               0 |
+-----------------+
1 row in set (0.00 sec)

mysql> SELECT ISNUMERIC('10a');
+------------------+
| ISNUMERIC('10a') |
+------------------+
|                0 |
+------------------+
1 row in set (0.00 sec)

mysql> SELECT ISNUMERIC('0.a');
+------------------+
| ISNUMERIC('0.a') |
+------------------+
|                0 |
+------------------+
1 row in set (0.00 sec)

mysql> SELECT ISNUMERIC('a.0');
+------------------+
| ISNUMERIC('a.0') |
+------------------+
|                0 |
+------------------+
1 row in set (0.00 sec)
Daniel Vassallo
A: 

In my case I just needed to check if data was >= 0 and not char, perhaps this is useful for you also:

mysql> select '1'  REGEXP '^[0-9]+$' as result;
+--------+
| result |
+--------+
|      1 | 
+--------+
1 row in set (0.16 sec)

mysql> select '1a'  REGEXP '^[0-9]+$' as result;
+--------+
| result |
+--------+
|      0 | 
+--------+
gonzalemario