MySQL query to return only the rows which are numeric?


Use REGEXP to return only the numeric rows. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> StudentId varchar(100)
   -> );
Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John74747');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('8494575Carol');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values('985755645');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values('Carol-9032');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values('101');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+--------------+
| StudentId    |
+--------------+
| John74747    |
| 8494575Carol |
| 985755645    |
| Carol-9032   |
| 101          |
+--------------+
5 rows in set (0.00 sec)

Following is the query to return only the rows which are numeric −

mysql> select *from DemoTable where StudentId REGEXP '^[0-9]+$';

Output

+-----------+
| StudentId |
+-----------+
| 985755645 |
| 101       |
+-----------+
2 rows in set (0.17 sec)

Updated on: 30-Jul-2019

655 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements