Using LIKE for two where clauses in MySQL?


You don’t need to use two where clauses. Use two conditions using the LIKE operator and AND operator.

To understand how to use LIKE for this, let us create a table. The query to create a table is as follows −

mysql> create table WhereDemo
   -> (
   -> Id int,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.56 sec)

Now you can insert some records in the table using insert command. The query is as follows −

mysql> insert into WhereDemo values(101,'Maxwell');
Query OK, 1 row affected (0.14 sec)
mysql> insert into WhereDemo values(110,'David');
Query OK, 1 row affected (0.21 sec)
mysql> insert into WhereDemo values(1000,'Carol');
Query OK, 1 row affected (0.18 sec)
mysql> insert into WhereDemo values(1100,'Bob');
Query OK, 1 row affected (0.47 sec)
mysql> insert into WhereDemo values(115,'Sam');
Query OK, 1 row affected (0.23 sec)

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

mysql> select *from WhereDemo;

The following is the output −

+------+---------+
| Id   | Name    |
+------+---------+
| 101  | Maxwell |
| 110  | David   |
| 1000 | Carol   |
| 1100 | Bob     |
| 115  | Sam     |
+------+---------+
5 rows in set (0.00 sec)

Here is the demo with the LIKE operator. The query is as follows −

mysql> select *from WhereDemo t1 where t1.Id LIKE '%1100%' AND t1.Name LIKE '%Bob%';

The following is the output −

+------+------+
| Id   | Name |
+------+------+
| 1100 | Bob  |
+------+------+
1 row in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements