How to check if any of the strings in a column contains a specific string in MySQL?


For this, use CONCAT() along with LIKE operator. Let us first create a table −

mysql> create table DemoTable
(
   Name varchar(40)
);
Query OK, 0 rows affected (0.56 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.33 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('Johnson');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+---------+
| Name    |
+---------+
| John    |
| Adam    |
| Bob     |
| Johnson |
| David   |
+---------+
5 rows in set (0.00 sec)

Following is the query to check if any of the strings in a column contains a specific string −

mysql> select *from DemoTable where Name like "%Joh%" OR "Joh" LIKE CONCAT("%", Name, "%");

This will produce the following output −

+---------+
| Name    |
+---------+
| John    |
| Johnson |
+---------+
2 rows in set (0.00 sec)

Updated on: 09-Oct-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements