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



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)
Updated on: 2019-09-24T12:36:49+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements