How can I select only those rows where first digit is a number from 0 to 9 in MySQL?


To select only those rows where first digit is a number from 0 to 9, use RLIKE.

 Following is the syntax −

select *from yourTableName where yourColumnName RLIKE '^[0-9]+'

Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   QuestionNumber varchar(200)
);
Query OK, 0 rows affected (0.56 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(QuestionNumber) values('1Question');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(QuestionNumber) values('Question2');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(QuestionNumber) values('311Question');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(QuestionNumber) values('45Question');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(QuestionNumber) values('Question10');
Query OK, 1 row affected (0.13 sec)

Following is the query to display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+----------------+
| Id | QuestionNumber |
+----+----------------+
| 1  | 1Question      |
| 2  | Question2      |
| 3  | 311Question    |
| 4  | 45Question     |
| 5  | Question10     |
+----+----------------+
5 rows in set (0.00 sec)

Here is the query to select only those rows where first digit is a number from 0 to 9 −

mysql> select *from DemoTable where QuestionNumber RLIKE '^[0-9]+';

This will produce the following output −

+----+----------------+
| Id | QuestionNumber |
+----+----------------+
| 1  | 1Question      |
| 3  | 311Question    |
| 4  | 45Question     |
+----+----------------+
3 rows in set (0.03 sec)

Updated on: 30-Jul-2019

884 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements