Comparing two strings in MySQL?


To compare two strings, which are numbers, let us first create a table. Following is the query −

mysql> create table compareTwoStringsDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Value varchar(100)
   -> );
Query OK, 0 rows affected (0.52 sec)

Following is the query to insert some records in the table using insert command −

mysql> insert into compareTwoStringsDemo(Value) values('1235667');
Query OK, 1 row affected (0.66 sec)

mysql> insert into compareTwoStringsDemo(Value) values('999999');
Query OK, 1 row affected (0.11 sec)

mysql> insert into compareTwoStringsDemo(Value) values('999888');
Query OK, 1 row affected (0.17 sec)

mysql> insert into compareTwoStringsDemo(Value) values('567433');
mysql> insert into compareTwoStringsDemo(Value) values('567433');
Query OK, 1 row affected (0.23 sec)

mysql> insert into compareTwoStringsDemo(Value) values('2345123');
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 compareTwoStringsDemo;

This will produce the following output −

+----+---------+
| Id | Value   |
+----+---------+
| 1  | 1235667 |
| 2  | 999999  |
| 3  | 999888  |
| 4  | 567433  |
| 5  | 2345123 |
+----+---------+
5 rows in set (0.00 sec)

Following is the query to compare two strings which are numbers −

mysql> select *from compareTwoStringsDemo
-> where cast(Value as signed) = 999999;

This will produce the following output. The record with the matching string gets displayed −

+----+--------+
| Id | Value  |
+----+--------+
| 2  | 999999 |
+----+--------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements