Performing a MySQL LIKE comparison on an INT field?


You need to use cast() method to perform comparison on an INT field. The syntax is as follows −

SELECT yourColumnName1,yourColumnName2,......N yourTableName WHERE CAST(yourColumnName as CHAR) LIKE ‘%yourIntegerValue%’;

To understand the above syntax, let us create a table. The following is the query to create a table for performing a LIKE comparison on INT field −

mysql> create table ComparisonOnIntField
   -> (
   -> StudentId int NOT NULL,
   -> StudentName varchar(20),
   -> StudentAge int
   -> );
Query OK, 0 rows affected (1.00 sec)

Insert some records in the table to perform a MySQL LIKE comparison on an INT field. The query to insert record is as follows −

mysql> insert into ComparisonOnIntField values(10,'Carol',24);
Query OK, 1 row affected (0.17 sec)

mysql> insert into ComparisonOnIntField values(12,'Bob',21);
Query OK, 1 row affected (0.18 sec)

mysql> insert into ComparisonOnIntField values(14,'Sam',23);
Query OK, 1 row affected (0.10 sec)

mysql> insert into ComparisonOnIntField values(16,'Mike',25);
Query OK, 1 row affected (0.26 sec)

mysql> insert into ComparisonOnIntField values(18,'John',27);
Query OK, 1 row affected (0.14 sec)

mysql> insert into ComparisonOnIntField values(20,'David',26);
Query OK, 1 row affected (0.15 sec)

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

mysql> select *from ComparisonOnIntField;

The following is the output.

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|        10 | Carol       |         24 |
|        12 | Bob         |         21 |
|        14 | Sam         |         23 |
|        16 | Mike        |         25 |
|        18 | John        |         27 |
|        20 | David       |         26 |
+-----------+-------------+------------+
6 rows in set (0.00 sec)

Here is the query to perform a MySQL LIKE comparison on an INT field −

mysql> select StudentName,StudentAge from ComparisonOnIntField
    -> where cast(StudentId as CHAR) Like '%18%';

The following is the output −

+-------------+------------+
| StudentName | StudentAge |
+-------------+------------+
| John        |         27 |
+-------------+------------+
1 row in set (0.05 sec)

Updated on: 30-Jul-2019

454 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements