How to compare two strings which are numbers in MySQL?

MySQLMySQLi Database

To compare two strings which are numbers in MySQL, use the CAST() function.

The syntax is as follows

select *from yourTableName
where cast(yourColumnName as signed)=yourIntegerValue;

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

mysql> create table compareTwoStringDemo
   -> (
   -> UserId varchar(100)
   -> );
Query OK, 0 rows affected (0.78 sec)

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

mysql> insert into compareTwoStringDemo values('1083745');
Query OK, 1 row affected (0.12 sec)
mysql> insert into compareTwoStringDemo values('9867585');
Query OK, 1 row affected (0.11 sec)
mysql> insert into compareTwoStringDemo values('3547483');
Query OK, 1 row affected (0.15 sec)
mysql> insert into compareTwoStringDemo values('9845646');
Query OK, 1 row affected (0.15 sec)
mysql> insert into compareTwoStringDemo values('9876532');
Query OK, 1 row affected (0.10 sec)

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

mysql> select *from compareTwoStringDemo;

The following is the output

+---------+
| UserId  |
+---------+
| 1083745 |
| 9867585 |
| 3547483 |
| 9845646 |
| 9876532 |
+---------+
5 rows in set (0.00 sec)

Here is the query to compare two strings which are numbers

mysql> select *from compareTwoStringDemo
   -> where cast(UserId as signed)=3547483;

The following is the output

+---------+
| UserId  |
+---------+
| 3547483 |
+---------+
1 row in set (0.00 sec)
raja
Published on 01-Apr-2019 12:14:35
Advertisements