Computer >> Computer tutorials >  >> Programming >> MySQL

How to use % wildcard correctly in MySQL?


You can use Like operator for working with % wildcard. The syntax is as follows

select *from yourTableName
where yourColumName Like ‘condition%’;

To understand the above concept, let us first create a table. The query to create a table

mysql> create table SearchDemo
   -> (
   -> Name varchar(100),
   -> LoginId varchar(100)
   -> );
Query OK, 0 rows affected (1.15 sec)

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

mysql> insert into SearchDemo values('John','1_1');
Query OK, 1 row affected (0.19 sec)

mysql> insert into SearchDemo values('Johnson','1_2');
Query OK, 1 row affected (0.19 sec)

mysql> insert into SearchDemo values('Carol','2_1');
Query OK, 1 row affected (0.12 sec)

mysql> insert into SearchDemo values('Bob','11_1');
Query OK, 1 row affected (0.19 sec)

mysql> insert into SearchDemo values('Sam','11_2');
Query OK, 1 row affected (0.25 sec)

mysql> insert into SearchDemo values('Mike','21_1');
Query OK, 1 row affected (0.22 sec)

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

mysql> select *from SearchDemo;

The following is the output

+---------+---------+
| Name    | LoginId |
+---------+---------+
| John    | 1_1     |
| Johnson | 1_2     |
| Carol   | 2_1     |
| Bob     | 11_1    |
| Sam     | 11_2    |
| Mike    | 21_1    |
+---------+---------+
6 rows in set (0.00 sec)

The % is a type of wildcard that represents zero, one, or multiple characters. The query is as follows using the % wildcard

mysql> select *from SearchDemo
   -> where LoginId Like '2%';

The following is the output

+-------+---------+
| Name  | LoginId |
+-------+---------+
| Carol | 2_1     |
| Mike  | 21_1    |
+-------+---------+
2 rows in set (0.00 sec)