Fetch records from comma separated values using MySQL IN()?



Use FIND_IN_SET() instead of MySQL IN(). Let us first create a −

mysql> create table DemoTable1423    -> (    -> CountryName varchar(100)    -> ); Query OK, 0 rows affected (0.51 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1423 values('AUS,UK'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable1423 values('US'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1423 values('AUS,UK,US'); Query OK, 1 row affected (0.13 sec)

Display all records from the table using select −

mysql> select * from DemoTable1423;

This will produce the following output −

+-------------+ | CountryName | +-------------+ | AUS,UK      | | US          | | AUS,UK,US   | +-------------+ 3 rows in set (0.00 sec)

Here is the query to fetch records using FIND_IN_SET()−

mysql> select * from DemoTable1423 where find_in_set('US',CountryName);

This will produce the following output −

+-------------+ | CountryName | +-------------+ | US          | | AUS,UK,US   | +-------------+ 2 rows in set (0.00 sec)
Updated on: 2019-11-12T05:42:44+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements