MySQL query to check if a string contains a value (substring) within the same row?

MySQLMySQLi Database

Since we need to match strings from the same row, use LIKE operator. Let us first create a table −

mysql> create table DemoTable
(
   FirstName varchar(100),
   FullName varchar(100)
);
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('John','John Smith');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('David','John Miller');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Bob','Sam Miller');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Chris','Chris Brown');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+-------------+
| FirstName | FullName    |
+-----------+-------------+
| John      | John Smith  |
| David     | John Miller |
| Bob       | Sam Miller  |
| Chris     | Chris Brown |
+-----------+-------------+
4 rows in set (0.00 sec)

Following is the query to check if a string contains a value within the same row −

mysql> select FirstName,FullName from DemoTable
   where FullName LIKE concat('%', FirstName, '%');

This will produce the following output −

+-----------+-------------+
| FirstName | FullName    |
+-----------+-------------+
| John      | John Smith  |
| Chris     | Chris Brown |
+-----------+-------------+
2 rows in set (0.00 sec)
raja
Published on 24-Sep-2019 12:35:00
Advertisements