Check if a string contains numbers in MySQL?


To check a string contains numbers, you can use regexp i.e. Regular Expressions. The syntax is as follows −

SELECT *FROM yourTableName where yourColumnName REGEXP ‘[0-9]’;

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table StringContainsNumber
   -> (
   -> Id int not null auto_increment,
   -> Words text,
   -> primary key(Id)
   -> );
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into StringContainsNumber(Words) values('He12345llo');
Query OK, 1 row affected (0.19 sec)

mysql> insert into StringContainsNumber(Words) values('MySQL is not a programming
4language');
Query OK, 1 row affected (0.17 sec)

mysql> insert into StringContainsNumber(Words) values('Java is an object oriented');
Query OK, 1 row affected (0.18 sec)

mysql> insert into StringContainsNumber(Words) values('Java does not support 456 multiple
inheritance');
Query OK, 1 row affected (0.20 sec)

mysql> insert into StringContainsNumber(Words) values('MySQL is a RDBMS 456');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from StringContainsNumber;

The following is the output.

+----+------------------------------------------------+
| Id | Words                                          |
+----+------------------------------------------------+
|  1 | He12345llo                                     |
|  2 | MySQL is not a programming 4language           |
|  3 | Java is an object oriented                     |
|  4 | Java does not support 456 multiple inheritance |
|  5 | MySQL is a RDBMS 456                           |
+----+------------------------------------------------+
5 rows in set (0.00 sec)

Here is the query to find the string that has numbers using REGEXP −

mysql> select *from StringContainsNumber where Words regexp '[0-9]';

The following is the output −

+----+------------------------------------------------+
| Id | Words                                          |
+----+------------------------------------------------+
|  1 | He12345llo                                     |
|  2 | MySQL is not a programming 4language           |
|  4 | Java does not support 456 multiple inheritance |
|  5 | MySQL is a RDBMS 456                           |
+----+------------------------------------------------+
4 rows in set (0.11 sec)

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements