Find specific records from a column with comma separated values in MySQL


For this, you can use FIND_IN_SET(). Let us first create a table −

mysql> create table DemoTable
   -> (
   -> ListOfValue varchar(20)
   -> );
Query OK, 0 rows affected (0.52 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('78,89,65');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('88,96,97');
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values('95,96,99,100');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('78,45,67,98');
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 −

+--------------+
| ListOfValue  |
+--------------+
| 78,89,65     |
| 88,96,97     |
| 95,96,99,100 |
| 78,45,67,98  |
+--------------+
4 rows in set (0.00 sec)

Following is the query to find specific records from a column with comma-separated values −

mysql> select * from DemoTable
   -> where find_in_set('89',ListOfValue)
   -> or
   -> find_in_set('99',ListOfValue);

This will produce the following output −

+--------------+
| ListOfValue  |
+--------------+
| 78,89,65     |
| 95,96,99,100 |
+--------------+
2 rows in set (0.00 sec)

Updated on: 28-Feb-2020

629 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements