Append wildcards in SELECT with MySQL?


For appending, use the concept of concat(). The syntax is as follows −

select *from yourTableName where yourColumnName like concat('%',yourValue,'%');

Let us create a table −

mysql> create table demo48
-> (
−> id int not null auto_increment primary key,
−> name varchar(20)
−> );
Query OK, 0 rows affected (0.70 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo48(name) values('John Smith');
Query OK, 1 row affected (0.12 sec)

mysql> insert into demo48(name) values('John Doe');
Query OK, 1 row affected (0.12 sec)

mysql> insert into demo48(name) values('Adam Smith');
Query OK, 1 row affected (0.23 sec)

mysql> insert into demo48(name) values('David Miller');
Query OK, 1 row affected (0.14 sec)

mysql> insert into demo48(name) values('Chris Brown');
Query OK, 1 row affected (0.11 sec)

Display records from the table using select statement −

mysql> select *from demo48;

This will produce the following output −

+----+--------------+
| id | name         |
+----+--------------+
|  1 | John Smith   |
|  2 | John Doe     |
|  3 | Adam Smith   |
|  4 | David Miller |
|  5 | Chris Brown  |
+----+--------------+
5 rows in set (0.00 sec)

Following is the query to append wildcards in select statement −

mysql> select *from demo48 where name like concat('%','Smith','%');

This will produce the following output −

+----+------------+
| id | name       |
+----+------------+
|  1 | John Smith |
|  3 | Adam Smith |
+----+------------+
2 rows in set (0.00 sec)

Updated on: 19-Nov-2020

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements