Searching from a comma separated MySQL column?


To search from a comma-separated column, use the FIND_IN_SET() method. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values('41,14,94');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('64,84,94');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('44,74,103,104');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('904,1004,1444,1544');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('4,144,174');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------------------+
| Value              |
+--------------------+
| 41,14,94           |
| 64,84,94           |
| 44,74,103,104      |
| 904,1004,1444,1544 |
| 4,144,174          |
+--------------------+
5 rows in set (0.00 sec)

Here is the query to search from a comma-separated MySQL column −

mysql> select *from DemoTable where find_in_set('4',Value);

This will produce the following output −

+-----------+
| Value     |
+-----------+
| 4,144,174 |
+-----------+
1 row in set (0.00 sec)

Updated on: 12-Dec-2019

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements