Syntax error Get the strings in the table records that ends with numbers?

Get the strings in the table records that ends with numbers?



You need to use REGEXP for this. The syntax is as follows −

select *from yourTableName where yourColumnName REGEXP '[[:digit:]]$';

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

mysql> create table StringEndsWithNumber
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserId varchar(20),
   -> UserName varchar(20)
   -> );
Query OK, 0 rows affected (0.62 sec)

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

mysql> insert into StringEndsWithNumber(UserId,UserName) values('123User','John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into StringEndsWithNumber(UserId,UserName) values('User456','Larry');
Query OK, 1 row affected (0.19 sec)
mysql> insert into StringEndsWithNumber(UserId,UserName) values('User789','John');
Query OK, 1 row affected (0.12 sec)
mysql> insert into StringEndsWithNumber(UserId,UserName) values('0981User','Carol');
Query OK, 1 row affected (0.17 sec)
mysql> insert into StringEndsWithNumber(UserId,UserName) values('User999','Bob');
Query OK, 1 row affected (0.14 sec)
mysql> insert into StringEndsWithNumber(UserId,UserName) values('User1290','David');
Query OK, 1 row affected (0.37 sec)
mysql> insert into StringEndsWithNumber(UserId,UserName) values('User456','James');
Query OK, 1 row affected (0.21 sec)

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

mysql> select *from StringEndsWithNumber;

Output

+----+----------+----------+
| Id | UserId   | UserName |
+----+----------+----------+
|  1 | 123User  | John     |
|  2 | User456  | Larry    |
|  3 | User789  | John     |
|  4 | 0981User | Carol    |
|  5 | User999  | Bob      |
|  6 | User1290 | David    |
|  7 | User456  | James    |
+----+----------+----------+
7 rows in set (0.00 sec)

Here is the query where the string ends with numbers −

mysql> select *from StringEndsWithNumber where UserId REGEXP '[[:digit:]]$';

Output

+----+----------+----------+
| Id | UserId   | UserName |
+----+----------+----------+
|  2 | User456  | Larry    |
|  3 | User789  | John     |
|  5 | User999  | Bob      |
|  6 | User1290 | David    |
|  7 | User456  | James    |
+----+----------+----------+
5 rows in set (0.11 sec)
Updated on: 2019-07-30T22:30:25+05:30

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements