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

How to restrict MySQL `LIKE` operator to begin with specific characters?


Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('Mike');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Sam');
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+
|FirstName  |
+-----------+
| John      |
| Adam      |
| David     |
| Mike      |
| Sam       |
+-----------+
5 rows in set (0.00 sec)

Following is the query to restrict `LIKE` operator to begin with specific characters −

mysql> select *from DemoTable where FirstName LIKE 'D%' or FirstName LIKE 'S%';

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| David     |
| Sam       |
+-----------+
2 rows in set (0.00 sec)