In MySQL, is there a way to turn column records into a list?



Yes, we can turn a column records into a list using the MySQL GROUP_CONCAT(). Let us first create a table −

mysql> create table DemoTable    -> (    -> ClientId int,    -> ClientName varchar(20)    -> ); Query OK, 0 rows affected (0.88 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,'Chris'); Query OK, 1 row affected (0.54 sec) mysql> insert into DemoTable values(100,'Robert'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(100,'Adam'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(100,'David'); Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----------+------------+ | ClientId | ClientName | +----------+------------+ |      100 | Chris      | |      100 | Robert     | |      100 | Adam       | |      100 | David      | +----------+------------+ 4 rows in set (0.00 sec)

Here is the query to turn column records into a list −

mysql> select ClientId,group_concat(ClientName separator ',') from DemoTable group by ClientId;

This will produce the following output −

+----------+----------------------------------------+ | ClientId | group_concat(ClientName separator ',') | +----------+----------------------------------------+ |      100 | Chris,Robert,Adam,David               | +----------+----------------------------------------+ 1 row in set (0.00 sec)
Updated on: 2019-12-13T05:44:31+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements